2012-03-15 39 views
0

我想將位圖轉換爲base64 string.i可以轉換爲從字符串位圖...但它似乎有一個問題時,從位圖轉換爲string.I希望你們可以給我一個手位圖Base64String

public static string BitmapToString(BitmapImage image) 
    { 

     Stream stream = image.StreamSource ; 
     Byte[] buffer = null; 
     if (stream != null && stream.Length > 0) 
     { 
      using (BinaryReader br = new BinaryReader(stream)) 
      { 
       buffer = br.ReadBytes((Int32)stream.Length); 
      } 
     } 

     return Convert.ToBase64String(buffer); 
    } 

它得到一個ArgumentNullException了未處理 值不能爲空。 參數名稱:inArray 返回時Convert.ToBase64String(緩衝區)

幫助?

+0

你確定你輸入了'if'嗎?我認爲問題在於圖像已從網址加載,因此沒有任何流。 – xanatos 2012-03-15 19:25:42

+0

does not enter the if..the thing is it that that that image.StreamSource is null .. but it does獲得正確的圖像 – 2012-03-15 19:28:52

+0

試試這個:http://stackoverflow.com/questions/553611/wpf-image-to-字節(接受的解決方案) – xanatos 2012-03-15 19:30:47

回答

1

首先,有必要使用一些位圖編碼器(PngBitmapEncoder例如)到BitmapImage數據保存到存儲器中。

public static byte[] EncodeImage(BitmapImage bitmapImage) 
{ 
    using (MemoryStream memoryStream = new MemoryStream()) 
    { 
     BitmapEncoder encoder = new PngBitmapEncoder(); 
     encoder.Frames.Add(BitmapFrame.Create(bitmapImage)); 
     encoder.Save(memoryStream); 
     return memoryStream.ToArray(); 
    } 
} 

然後只用Base64編碼對二進制數據進行編碼。

const string filePath = @"..."; 
const string outFilePath = @"..."; 
const string outBase64FilePath = @"..."; 

// Constuct test BitmapImage instance. 
BitmapImage bitmapImage = new BitmapImage(); 
bitmapImage.BeginInit(); 
bitmapImage.StreamSource = File.OpenRead(filePath); 
bitmapImage.CacheOption = BitmapCacheOption.OnLoad; 
bitmapImage.EndInit(); 

// Convert BitmapImage to byte array. 
byte[] imageData = EncodeImage(bitmapImage); 
File.WriteAllBytes(outFilePath, imageData); 

// Encode with Base64. 
string base64String = Convert.ToBase64String(imageData); 

// Write to file (for example). 
File.WriteAllText(outBase64FilePath, base64String); 
相關問題