Click here to Skip to main content
15,896,727 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......



VB
Public Function SaveBase64ToImage(ByVal base64 As String)
        Try
            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!

VB
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
Posted
Updated 28-Oct-14 4:24am
v3
Comments
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
ErrorCode=-2147467259
HResult=-2147467259
Message=A generic error occurred in GDI+.
Source=System.Drawing
StackTrace:
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
InnerException:

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
 
v2

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