如何将位图转换为 Base64 字符串? [英] How to convert Bitmap to a Base64 string?

查看:29
本文介绍了如何将位图转换为 Base64 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

使用richTextBox调试,显示:

Using a richTextBox to debug, it shows:

BM6~

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

So for some reason the bytes aren't correct which causes the base64String to become null. Any idea what I'm doing wrong? Thanks.

推荐答案

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

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;

这篇关于如何将位图转换为 Base64 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆