Csharp/C#教程:如何将Bitmap转换为Base64字符串?分享


如何将Bitmap转换为Base64字符串?

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

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。 知道我做错了什么吗? 谢谢。

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

 // Convert byte[] to Base64 String string base64String = Convert.ToBase64String(imageBytes); // Write the bytes (as a Base64 string) to the textbox richTextBox1.Text = base64String; 

我找到了解决问题的方法:

 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 

不需要byte[] …只需直接转换流(使用构造)

上述就是C#学习教程:如何将Bitmap转换为Base64字符串?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)

 using (var ms = new MemoryStream()) { using (var bitmap = new Bitmap(newImage)) { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); var SigBase64= Convert.ToBase64String(ms.GetBuffer()); //Get Base64 } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ctvol.com/cdevelopment/1008083.html

(0)
上一篇 2021年12月29日
下一篇 2021年12月29日

精彩推荐