Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将位图转换为Base64字符串?_C#_Image_Base64 - Fatal编程技术网

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

C# 如何将位图转换为Base64字符串?,c#,image,base64,C#,Image,Base64,我试图捕获屏幕,然后将其转换为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);

我试图捕获屏幕,然后将其转换为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。知道我做错了什么吗?谢谢。

通过执行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;

我找到了解决问题的方法:

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

不需要
byte[]
…只需直接转换流(使用构造)


当OP使用BMP时,为什么有两个答案使用Jpeg格式?您可能希望另存为PNG,因为JPG会在加载图像后更改图像,然后将其保存回去。此外,如果您想进行图像比较,则只有在使用无损格式(如PNG)时才有可能
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
  }
}