Click here to Skip to main content
15,941,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would I convert a base64 png encoded string to a jpeg image and then save the jpeg to sql 2008 image field? The code below is used to show what I hope to achieve but breaks with a conversation error on the Imageformat.

The base64 string: data:image/png;base64,iVBORw0KGgoAA etc......

Public Function SaveBase64ToImage(ByVal base64 As String)
            Using ms As New MemoryStream(Convert.FromBase64String(base64))
                Using bm As New Bitmap(ms)
                    bm.Save(ms, System.Drawing.Imaging.ImageFormat.jpg)
                    Return bm
                End Using
            End Using
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

I have added a function to separate out the memory stream, but when I attempt to use the function to provide the data for the sql image save and then retrieve the image from the table and i get a black square and not the original image!

Public Shared Function ImageToBytes(img As Image) As Byte()
        If img Is Nothing Then Return Nothing
        Dim ms As New MemoryStream()
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)  
        Return ms.ToArray()
    End Function
Updated 28-Oct-14 4:24am
CPallini 28-Oct-14 6:51am    
What is the exact error message?
JoeBo747 28-Oct-14 7:13am    
I get the following:

System.Runtime.InteropServices.ExternalException was caught
Message=A generic error occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(Stream stream, ImageFormat format)
at PingToJpeg.TestForm.SaveBase64ToImage(String base64) in Z:\My Documents\Visual Studio 2012\Projects\Test Projects\PingToJpeg\PingToJpeg\TestForm.vb:line 124

1 solution

From "The Documentation"[^]:
You should avoid saving an image to the same stream that was used to construct it. Doing so might damage the stream.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900