Transmitting images through the network or API’s and Web service in programming is a little bit tricky. And the best way to do it is to convert images into a Base64 string. To put it simply, Base64 is an encoding schema used for interpreting binary data in a string format. This is beneficial when the storage or delivery means does not support binary data, such as when inserting an image into a database, CSS files, or HTML. One must be careful not to confuse compression with encoding. While compression actually compresses data, encoding defines how data is encoded, which brings us to the first issue. In this article, we will Convert an Image to Base64 String.
Note: Base64 encoding is not encryption. It is just done to safely transmit images or any big byte data without modification or being misinterpreted with other computer systems.
Tutorial Naming Guide
Function | Description |
ImgToBase64() | function use to generate baser64 string from an image (image to base64 Conversion) |
Base64ToImg() | function use to convert base64 string to an image object |
CreateImageObject() | function use to generate image object use for ImgToBase64() for testing |
Let’s start by declaring namespaces we need for the conversion:
NameSpace | Description |
using System.Drawing; | For creating new Image Object; |
using System.IO; | for memory stream, use to store our image in bytes |
Image to Base64 Conversion
public string ImgToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Base64 String to Image Conversion
public Image Base64ToImg(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);
// saving image to drive
image.Save(@"D:\image_saving\sample.jpg");
return image;
}
Creating an image Object » For Testing
public string CreateImageObject()
{
// Create image object
string path = @"C:\Users\Pictures\sample.jpg";
System.Drawing.Image img = System.Drawing.Image.FromFile(path, true);
// Pass image parameter to Convert in Base64
string b64 = ImgToBase64(img, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Happy Coding.
Visit my Blog page for more latest post.