2017-05-29 188 views
0

我試圖將Base64編碼的字符串轉換爲Png圖像,但代碼顯示參數的例外在Image.FromStream()上無效。調試後,我在MemoryStream對象上發現了這個錯誤「ReadTimeout ='ms.ReadTimeout'拋出了'System.InvalidOperationException'類型的異常。我卡住了,是否有任何解決方案或選擇將字符串轉換爲Png在C#中?如何將Base64字符串轉換爲Png圖像Mvc5 C#?

這裏是我的代碼

string code = "string"; 
var databytes = Encoding.Unicode.GetBytes(code); 
var base64 = Convert.ToBase64String(databytes); 
Byte[] Bytes = Convert.FromBase64String(base64); 
//Stream bytes 
MemoryStream ms = new MemoryStream(Bytes, 0, Bytes.Length); 
//convert image 

Image newImage = Image.FromStream(ms); 
newImage.Save("~/Content/");  

回答

1

試試這個:

byte[] bytes = Convert.FromBase64String(base64); 
Image image; 
using (MemoryStream ms = new MemoryStream(bytes)) 
{ 
    image = Image.FromStream(ms); 
} 
1

您可以Base64編碼字符串轉換成PNG這樣:

byte[] bytes = Convert.FromBase64String(base64); 

    Image image; 
    using (MemoryStream ms = new MemoryStream(bytes)) 
    { 
     image = Image.FromStream(ms); 
     image.Save("~/Content/", System.Drawing.Imaging.ImageFormat.Png); 
    } 
+0

我試過了,但正如我提到的它在Image.FromStream(ms)處顯示異常,例外是ReadTimeout ='ms.ReadTimeout'拋出了一個類型爲'System.InvalidOperationExce ption' –

+0

我將_image.Save_部分移動到_using_塊中並更新了答案。它可以解決你的錯誤。 – kkakkurt

+0

我試過了,但同樣的錯誤{{「參數無效」。}發生在Image.FromStream(ms)行 –

相關問題