Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert octet stream base64 string to image

Tags:

c#

image

base64

I want to convert the application/octet-stream base 64 string into image in c#. Please help me with this conversion.

Here is the string: ERQVHykzPkpWY3F/jp2tvMnU3ubs8fX5+/z8/Pr39PDq5d/Y0cvCu7Oro5uTjIR9dm9pY11ZVFBMSUZEQT47OTY0MjAuLSopJyUjIR8eHBsZGRcWFRUUExMSEREQDw8ODg4ODg0NDAwLCwoKCgoKCwsLDA0NDQ4ODg4ODw8QERI=

like image 596
Pravin G Avatar asked Sep 04 '26 23:09

Pravin G


1 Answers

Your base64 string contains an encoded binary file. The MIME type is application/octet-stream for a binary file. You'll only be able to convert base64 strings of image/octet-stream MIME type files.

Having said that, you can onvert your base64 string of a image/octet-stream MIME type file into a bytes array and then use a MemoryStream to compose an image from it.

using System.Drawing;

public static Image LoadBase64(string base64)
{
    byte[] bytes = Convert.FromBase64String(base64);
    MemoryStream ms = new MemoryStream(bytes)
    Image image = Image.FromStream(ms);
    
    return image;
}

Usage

Image myImage = LoadBase64(base64string);

Alternative

You could use the ImageConverter class which implements the ConvertFrom() method. It allows you to convert a specified object to an image.

public Image byteArrayToImage(byte[] byteArray)
{
    System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
    Image image = (Image)converter.ConvertFrom(byteArray);

    return image;
}
like image 99
ɐsɹǝʌ ǝɔıʌ Avatar answered Sep 06 '26 12:09

ɐsɹǝʌ ǝɔıʌ