簡體   English   中英

如何將Bitmap轉換為Base64字符串?

[英]How to convert Bitmap to a Base64 string?

我正在嘗試捕獲屏幕,然后將其轉換為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。 知道我做錯了什么嗎? 謝謝。

我找到了解決問題的方法:

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

通過執行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;

不需要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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM