我创建了一个位图截图:
Bitmap screenshot = TakeScreenshot();
byte[] bytes = ImageToByte(screenshot, System.Drawing.Imaging.ImageFormat.Bmp);
Run Code Online (Sandbox Code Playgroud)
现在我尝试编码:
string imageData = Encoding.UTF8.GetString(bytes);
Run Code Online (Sandbox Code Playgroud)
但是,如果我在我的富文本框中输出此字符串,那么我得到的结果是:
BM6?~
Run Code Online (Sandbox Code Playgroud)
即使长度imageData是8277082
到底是怎么回事?
功能:
public static byte[] ImageToByte(Image img, System.Drawing.Imaging.ImageFormat format)
{
using (var stream = new System.IO.MemoryStream()) {
img.Save(stream, format);
return stream.ToArray();
}
}
private Bitmap TakeScreenshot()
{
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap. (geht auch ohne das using gedöns, aber mit using ist es besser)
using (var gfxScreenshot = Graphics.FromImage(bmpScreenshot)) {
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
return bmpScreenshot;
}
Run Code Online (Sandbox Code Playgroud)
您不能使用Encoding.UTF8.GetString实际上不代表字符串的内容.编码失败(如您所见),您需要使用可以处理任意字节的编码,如Base 64编码
string imageData = Convert.ToBase64String(bytes);
Run Code Online (Sandbox Code Playgroud)
在服务器上获取您使用的字节数
byte[] imageDataAsBytes = Convert.FromBase64String(imageDataAsString);
Run Code Online (Sandbox Code Playgroud)
有一点需要注意,使用base 64编码将导致字符串占用原始大小的4/3(以字节为单位).如果可能,尝试调查是否可以将原始字节[]发送到服务器而不是首先将其编码为字符串,这将减少传输的数据.
您试图在字符串中表示二进制数据,但字符串不能表示每个二进制数据.
如果你想要一个字符串,那么你需要使用某种形式的编码作为最常见的Base64.
更改
string imageData = Encoding.UTF8.GetString(bytes);
Run Code Online (Sandbox Code Playgroud)
至
string imageData = Convert.ToBase64String(bytes);
Run Code Online (Sandbox Code Playgroud)
请记住,要恢复原始二进制数据,您必须对其进行解码:
byte[] data = Convert.FromBase64String(imageData);
Run Code Online (Sandbox Code Playgroud)