Steve Gray
Steve Gray

Reputation: 127

Convert an image from 'iVBORw0KGgoAAAANSUhEUgAAAx8AA...' to an image file

I'm not sure of the name of the format that I'm receiving this data in, but it always begins with 'iVBORw0KGgoAAAANSUhEUgAAAx8AA...' and they tell me it's a png.

I need to save this to disk and view the png file.

When I save it as is, I get 'not a valid format' type of error, so I'm thinking I need to convert it somehow.

Can anyone offer any help? (I'm doing this in .NET)

Edit: After looking an the suggestion below, I found this piece of code that worked:

Function Base64ToImage(ByVal base64string As String) As System.Drawing.Image
    'Setup image and get data stream together
    Dim img As System.Drawing.Image
    Dim MS As System.IO.MemoryStream = New System.IO.MemoryStream
    Dim b64 As String = base64string.Replace(" ", "+")
    Dim b() As Byte

    'Converts the base64 encoded msg to image data
    b = Convert.FromBase64String(b64)
    MS = New System.IO.MemoryStream(b)

    'creates image
    img = System.Drawing.Image.FromStream(MS)

    Return img
End Function

Upvotes: 0

Views: 85

Answers (2)

Trympet
Trympet

Reputation: 75

The PNG image is encoded as a base64 string. All you need to do is convert the string into a byte array, and write it to disk.

string pngImage = "iVBORw0KGgoAAAANSUhEUgAAAx8AA..."; // base64 string
byte[] pngByteArray = Convert.FromBase64String(pngImage);
string path = "C:\\Users\\etc\\etc\\image.png";
File.WriteAllBytes(path, pngByteArray); // Saves the image to disk

Upvotes: 0

Ravindra Bagale
Ravindra Bagale

Reputation: 17675

It is base64 string.. you need to convert base64 to image

Upvotes: 1

Related Questions