How to convert Bitmap to a Base64 string?(如何将位图转换为 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 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将位图转换为 Base64 字符串?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01