Converting and image to base 64 from an image or from a path or converting a base 64 string to an image is quite easy. We will use MemoryStream to convert them. We will use two simple method one to convert the image to base 64 string and other to convert the base 64 string to image. Image can be saved wherever you want or show them anywhere on the page
Code to convert the image into base 64 string by passing the image page, if you are using asp.net or web page then you need to use Server.MapPath to get the correct image path than absolute path
public String ConvertImageToBase64String(String imagePath)
{
using (var img = System.Drawing.Image.FromFile(imagePath))
{
using (var memStream = new MemoryStream())
{
img.Save(memStream, img.RawFormat);
byte[] imageBytes = memStream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
First we convert the image path into image, then save this image into memory and finally converted into base 64 string.
Now we will write the code to convert the base 64 string into image, we will pass base 64 string as parameter and then convert it into bytes and then to memory string and finally to image.
public System.Drawing.Image Base64StringToImage(string base64String)
{
byte[] imageBytes = Convert.FromBase64String(base64String);
var memStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
memStream.Write(imageBytes, 0, imageBytes.Length);
var image = System.Drawing.Image.FromStream(memStream);
return image;
}
If you want to save this image in any folder simple use image.save method to save it.
No comments:
Post a Comment