如何将位图转换为Base64字符串?

64

我正在尝试捕获屏幕并将其转换为Base64字符串。这是我的代码:

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);

使用richTextBox进行调试,它显示:

BM6�~

因此,由于某种原因字节不正确导致base64String变为null。有没有什么想法,我做错了什么?谢谢。

3个回答

79
我找到了解决我的问题的方法:
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

40

通过执行System.Text.Encoding.UTF8.GetString(imageBytes)得到的字符(几乎肯定)包含不可打印的字符。这可能会导致您只看到那几个字符。如果您先将其转换为Base64字符串,则它将仅包含可打印字符,并且可以显示在文本框中:

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

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

21

不需要 byte[]... 直接将流转换(使用“using”结构)即可

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

为什么两个回答使用JPEG格式,而原帖使用BMP格式? - KansaiRobot
2
你可能想要保存为PNG格式,因为如果你加载并重新保存JPG格式的图像,则会更改图像。此外,如果您想进行图像比较,则仅在使用无损格式(如PNG)时才可能。 - TravisO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接