简体   繁体   中英

Convert octet stream base64 string to image

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=

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM