2011-08-30 4 views
7

Я хочу преобразовать изображение в base64 и снова вернуться к изображению. Вот код, который я пробовал до сих пор, и ошибка. Любые предложения, пожалуйста?Преобразование изображения в base64 и наоборот

public void Base64ToImage(string coded) 
{ 
    System.Drawing.Image finalImage; 
    MemoryStream ms = new MemoryStream(); 
    byte[] imageBytes = Convert.FromBase64String(coded); 
    ms.Read(imageBytes, 0, imageBytes.Length); 
    ms.Seek(0, SeekOrigin.Begin); 
    finalImage = System.Drawing.Image.FromStream(ms); 

    Response.ContentType = "image/jpeg"; 
    Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorner.jpg"); 
    finalImage.Save(Response.OutputStream, ImageFormat.Jpeg); 
} 

Ошибка:

Parameter is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Parameter is not valid.

Source Error:

Line 34:    ms.Read(imageBytes, 0, imageBytes.Length); 
Line 35:    ms.Seek(0, SeekOrigin.Begin); 
Line 36:    finalImage = System.Drawing.Image.FromStream(ms); 
Line 37:   
Line 38:   Response.ContentType = "image/jpeg"; 

Source File: e:\Practice Projects\FaceDetection\Default.aspx.cs Line: 36

ответ

7

Вы чтение из пустого потока, а не загрузки существующих данных (imageBytes) в по течению. Попробуйте:

byte[] imageBytes = Convert.FromBase64String(coded); 
using(var ms = new MemoryStream(imageBytes)) { 
    finalImage = System.Drawing.Image.FromStream(ms); 
} 

Кроме того, вы должны стремиться к тому, что finalImage расположен; Я хотел бы предложить:

System.Drawing.Image finalImage = null; 
try { 
    // the existing code that may (or may not) successfully create an image 
    // and assign to finalImage 
} finally { 
    if(finalImage != null) finalImage.Dispose(); 
} 

И, наконец, обратите внимание, что System.Drawing is not supported на ASP.NET; YMMV.

Caution

Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.

+0

все еще получаю тот же ошибка в строке finalImage = System.Drawing.Image.FromStream (ms); –

2

MemoryStream.Read Method считывает байты из MemoryStream в указанный массив байтов.

Если вы хотите записать массив в MemoryStream, используйте MemoryStream.Write Method:

ms.Write(imageBytes, 0, imageBytes.Length); 
ms.Seek(0, SeekOrigin.Begin); 

В качестве альтернативы, вы можете просто обернуть массив байтов в MemoryStream:

MemoryStream ms = new MemoryStream(imageBytes); 
+0

Спасибо за ответ, но не сработал! Можете ли вы предложить какие-либо альтернативы? –

Смежные вопросы