【问题标题】:How to convert Bitmap to a Base64 string?如何将位图转换为 Base64 字符串?
【发布时间】:2012-06-04 23:31:14
【问题描述】:

我正在尝试捕获屏幕,然后将其转换为 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 变为空。知道我做错了什么吗?谢谢。

【问题讨论】:

    标签: c# image base64


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      通过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;
      

      【讨论】:

        【解决方案3】:

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

        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
          }
        }
        

        【讨论】:

        • 当OP使用BMP时,为什么两个答案都使用Jpeg格式??
        • 您可能希望另存为 PNG,因为 JPG 会在您加载图像后更改图像,然后将其保存回来。此外,如果您想进行图像比较,那么只有在使用无损格式(如 PNG)时才有可能
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        • 2021-11-09
        • 1970-01-01
        相关资源
        最近更新 更多