简体   繁体   English

如何将Bitmap转换为Base64字符串?

[英]How to convert Bitmap to a Base64 string?

I'm trying to capture the screen and then convert it to a Base64 string. 我正在尝试捕获屏幕,然后将其转换为Base64字符串。 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: 使用richTextBox进行调试,它显示:

BM6 ~ BM6〜

So for some reason the bytes aren't correct which causes the base64String to become null. 因此,由于某种原因,字节不正确会导致base64String变为null。 Any idea what I'm doing wrong? 知道我做错了什么吗? Thanks. 谢谢。

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

The characters you get by doing System.Text.Encoding.UTF8.GetString(imageBytes) will (almost certainly) contain unprintable characters. 通过执行System.Text.Encoding.UTF8.GetString(imageBytes)获得的字符(几乎可以肯定)将包含不可打印的字符。 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: 如果您首先将其转换为base64字符串,那么它将只包含可打印字符,并可以显示在文本框中:

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

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

No need for byte[] ...just convert the stream directly (w/using constructs) 不需要byte[] ...只需直接转换流(使用构造)

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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM