How to convert Bitmap to a Base64 string?
我正在尝试捕获屏幕,然后将其转换为Base64字符串。这是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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。知道我在做什么错吗?谢谢。
我找到了解决问题的方法:
1 2 3 4 5 | 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 |
通过
1 2 3 4 5 | // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); // Write the bytes (as a Base64 string) to the textbox richTextBox1.Text = base64String; |
不需要
1 2 3 4 5 6 7 8 |