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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10889764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:39:48  来源:igfitidea点击:

How to convert Bitmap to a Base64 string?

c#imagebase64

提问by Joey Morani

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

我正在尝试捕获屏幕,然后将其转换为 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);

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. Any idea what I'm doing wrong? Thanks.

因此由于某种原因,字节不正确导致 base64String 变为空。知道我做错了什么吗?谢谢。

采纳答案by Tim S.

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:

您通过这样做获得的字符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;

回答by Hussain Ahmed Shamsi

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

回答by Onyximo

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