Windows Forms: Convert an image to base64 in C#
By FoxLearn 3/20/2020 11:13:59 AM 15.88K
You can create a new windows forms application project to play the demo, Next, Drag pictureboxes, labels and buttons from the visual studio toolbox to your winform, then design a simple UI that allows you to select an image from your disk, and then convert an image to base64 string or convert the base64 string encoded to image in c# as shown below.
To convert an image to base64 string, you can create a ConvertImageToBase64 method as shown below.
public string ConvertImageToBase64(Image file) { using (MemoryStream memoryStream = new MemoryStream()) { file.Save(memoryStream, file.RawFormat); byte[] imageBytes = memoryStream.ToArray(); return Convert.ToBase64String(imageBytes); } }
The ConvertImageToBase64 read an image, then save the image into memory stream and convert to base64 string.
Similarly, to convert a base64 string encoded to an image, you can create a ConvertBase64ToImage method as shown below.
public Image ConvertBase64ToImage(string base64String) { byte[] imageBytes = Convert.FromBase64String(base64String); using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { ms.Write(imageBytes, 0, imageBytes.Length); return Image.FromStream(ms, true); } }
We will convert base64 string to byte arrays, then write into memory stream, finally return an image from the stream.
Next, Click on the Image To Base64 button, then add a click event handler in c# as the following code.
private void btnImageToBase64_Click(object sender, EventArgs e) { using (Image image = picOriginal.Image.Clone() as Image) { txtBase64.Text = ConvertImageToBase64(image); } }
You can clone data from the picturebox, then cast your object to image type.
Same for Base64 To Image button.
private void btnBase64ToImage_Click(object sender, EventArgs e) { picBase64ToImage.Image = ConvertBase64ToImage(txtBase64.Text); }