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

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

问题描述

我试图捕捉屏幕,然后将其转换为一个Base64字符串。这是我的code:

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天全站免登陆