Image to Base64string C#


This code snippet will help you to convert an image into a base64 string.
using (MemoryStream objMemoryStream = new MemoryStream())
{
string imgContentType = FileUploadLogo.PostedFile.ContentType;
 
// Convert Image to byte[]
switch (imgContentType)
{
case “image/jpeg”:
System.Drawing.Image.FromStream(FileUploadLogo.PostedFile.InputStream).Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case “image/gif”:
System.Drawing.Image.FromStream(FileUploadLogo.PostedFile.InputStream).Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Gif);
break;
case “image/bmp”:
System.Drawing.Image.FromStream(FileUploadLogo.PostedFile.InputStream).Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
break;
case “image/png”:
System.Drawing.Image.FromStream(FileUploadLogo.PostedFile.InputStream).Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Png);
break;
}
 
byte[] objImageBytes = objMemoryStream.ToArray();
 
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(objImageBytes);
return base64String;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s