i'm working on a website that takes its data from a web service. Our Android developer gave me a Base64 string like this.
iVBORw0KGgoAAAANSUhEUgAAAKAAAAB4CAYAAAB1ovlvAAAABHNCSVQICAgIf. . . . . . . . . .
I'm saving this string to my database. I would like to know how I can convert this to an image.
Here is the solution for you
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
If you're showing it in a web page (You added asp.net as one of your tags so I'm assuming this is for the web) you can cheat and do this:
<img src="data:image/png;base64,<%=base64String%>"/>
This assumes that the image is a png, otherwise change it to image/jpg or whatever.
The downside is this stops the image being cached. So in practice the solution by @Sachin is more practical. This way is just neat if you want to avoid saving the files for whatever reason (or just want a 'I need it to work now' solution)
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.