How to convert Bitmap to a Base64 string?

C#ImageBase64

C# Problem Overview


I'm trying to capture the screen and then convert it to a Base64 string. This is my code:

Rectangle bounds = Screen.GetBounds(Point.Empty);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);

using (Graphics g = Graphics.FromImage(bitmap))
{
   g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}

// Convert the image to byte[]
System.IO.MemoryStream stream = new System.IO.MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();

// Write the bytes (as a string) to the textbox
richTextBox1.Text = System.Text.Encoding.UTF8.GetString(imageBytes);

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);

Using a richTextBox to debug, it shows:

> BM6�~

So for some reason the bytes aren't correct which causes the base64String to become null. Any idea what I'm doing wrong? Thanks.

C# Solutions


Solution 1 - C#

I found a solution for my issue:

Bitmap bImage = newImage;  // Your Bitmap Image
System.IO.MemoryStream ms = new MemoryStream();
bImage.Save(ms, ImageFormat.Jpeg);
byte[] byteImage = ms.ToArray();
var SigBase64= Convert.ToBase64String(byteImage); // Get Base64

Solution 2 - C#

The characters you get by doing System.Text.Encoding.UTF8.GetString(imageBytes) will (almost certainly) contain unprintable characters. This could cause you to only see those few characters. If you first convert it to a base64-string, then it will contain only printable characters and can be shown in a text box:

// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);

// Write the bytes (as a Base64 string) to the textbox
richTextBox1.Text = base64String;

Solution 3 - C#

No need for byte[] ...just convert the stream directly (w/using constructs)

using (var ms = new MemoryStream())
{    
  using (var bitmap = new Bitmap(newImage))
  {
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    var SigBase64= Convert.ToBase64String(ms.GetBuffer()); //Get Base64
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoey MoraniView Question on Stackoverflow
Solution 1 - C#Hussain Ahmed ShamsiView Answer on Stackoverflow
Solution 2 - C#Tim S.View Answer on Stackoverflow
Solution 3 - C#OnyximoView Answer on Stackoverflow