2011-08-30 44 views
7

Tôi muốn chuyển đổi hình ảnh thành base64 và quay lại hình ảnh một lần nữa. Đây là mã mà tôi đã thử cho đến nay và cũng có lỗi. Bất kỳ đề nghị xin vui lòng?Chuyển đổi hình ảnh thành base64 và ngược lại

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); 
} 

Lỗi này là:

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

Trả lời

7

Bạn đang đọc từ một dòng sản phẩm nào, chứ không phải tải các dữ liệu hiện có (imageBytes) vào dòng. Hãy thử:

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

Ngoài ra, bạn nên cố gắng đảm bảo rằng finalImage được xử lý; Tôi sẽ đề xuất:

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(); 
} 

Và cuối cùng, lưu ý rằng System.Drawing is not supported trên 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

vẫn nhận được cùng lỗi trong dòng finalImage = System.Drawing.Image.FromStream (ms); –

2

MemoryStream.Read Method đọc byte từ MemoryStream vào mảng byte được chỉ định.

Nếu bạn muốn viết mảng byte đến MemoryStream, sử dụng MemoryStream.Write Method:

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

Ngoài ra, bạn chỉ có thể quấn mảng byte trong một MemoryStream:

MemoryStream ms = new MemoryStream(imageBytes); 
+0

Cảm ơn câu trả lời nhưng không hoạt động! Bạn có thể đề nghị bất kỳ lựa chọn thay thế nào không? –

Các vấn đề liên quan