2012-06-04 32 views
16

我想捕獲屏幕,然後將其轉換爲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變爲空。任何想法我做錯了什麼?謝謝。

回答

18

你通過做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; 
+0

啊,woops。謝謝蒂姆。 :) –

21

我找到我的問題的解決方案:

Bitmap bImage = newImage; //Your Bitmap Image 
System.IO.MemoryStream ms = new System.IO.MemoryStream(); 
bImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 
byte[] byteImage = ms.ToArray(); 
var SigBase64= Convert.ToBase64String(byteImage); //Get Base64 
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 
    } 
} 
相關問題