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이 배치 될 수 있도록 노력해야한다; ASP.NET에 그 System.Drawing is not supported주의, 마지막으로

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

을 그리고; 내가 제안 것이다 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

답변 주셔서 감사합니다,하지만 작동하지 않았다! 어떤 대안을 제안 해 주시겠습니까? –

관련 문제