Export to JPG throws UnsupportedImageFormatException

Aug 23, 2010 at 10:46 PM

I am trying to export a Map control to a JPG.

The Map derives from the Silverlight MultiScaleImage control. There was a problem writing out the control directly because I get the Pixel Access Security Exception. It seems like this workflow might gets around it.

The following code runs fine, and a file gets created, but it's empty. I also get the UnsupportedImageFormatException after the code has run (I can't tell where it's being generated from). What am I doing wrong?

        Dim sfd As SaveFileDialog = New SaveFileDialog()
        sfd.Filter = "Image Files (*.jpg)|*.jpg "
        If Not sfd.ShowDialog() Then
            Return
        End If

        Dim wb As WriteableBitmap = New WriteableBitmap(Map, Nothing)
        ImageTools.IO.Encoders.AddEncoder(Of JpegEncoder)()

        Dim mStream As MemoryStream = New MemoryStream()
        Dim write As StreamWriter = New StreamWriter(mStream)
        write.Write(wb)
        write.Flush()

        Dim myImage As Image = New Image()
        myImage.SetSource(mStream)

        Try
            Using stream As Stream = sfd.OpenFile()
                Dim encoder As JpegEncoder = New JpegEncoder()
                encoder.Encode(myImage, stream)
                mStream.Close()
                stream.Close()
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try