62

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.

Joey Morani
  • 25,431
  • 32
  • 84
  • 131

3 Answers3

78

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
Neuron
  • 5,141
  • 5
  • 38
  • 59
40

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;
Tim S.
  • 55,448
  • 7
  • 96
  • 122
21

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
  }
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Onyximo
  • 231
  • 3
  • 6
  • Why two answers are using Jpeg format when the OP used BMP?? – KansaiRobot Jul 04 '18 at 04:59
  • 2
    You probably want to save as a PNG as JPG will change the image if you load it up then save it back. Also if you want to do image comparison then it's only possible when using lossless formats like PNG – TravisO Mar 25 '19 at 19:33