2011-05-05 4 views
3

사용자의 이미지 파일 경로가 있어야하며 SQL Server 데이터베이스에 이미지를 저장해야합니다.ImageSource를 byte []로 변환하고 ImageSource로 다시 변환하는 방법은 무엇입니까?

나는 사용자로부터 파일을 얻을 방법

public static byte[] ImageToByteArray(BitmapSource bitmapSource) 
    { 
     byte[] imgAsByteArray = null; 

     if(bitmapSource != null) 
     { 
      imgAsByteArray = (new WriteableBitmap((BitmapSource)bitmapSource)).Pixels.SelectMany(p => new byte[] 
      { 

       (byte) p  , 
       (byte)(p >> 8 ), 
       (byte)(p >> 16), 
       (byte)(p >> 24) 

      }).ToArray(); 
     } 

     return imgAsByteArray; 
    } 

를 사용하여 [] 바이트하지만 지금은 내가 BitmapSource는로 다시 변환 할 수 없습니다 변환합니다. 내가 쓴 코드는 다시 예외

에게 코드 던져 변환 : 나는 라인 bitmapImage.SetSource (MS)에 예외가

public static BitmapSourcebyteArrayToImage(byte[] imageBytes) 
    { 
     BitmapImage bitmapImage = null; 
     using(MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) 
     { 
      bitmapImage = new BitmapImage(); 
      bitmapImage.SetSource(ms);  
     } 

     return (BitmapSource)bitmapImage; 
    } 

을;
예외 정보는

+0

어떤 줄에서 예외가 발생합니까? – ZoolWay

+0

line bitmapImage.SetSource (ms); – Yanshof

+0

이미지 형식은 jpg – Yanshof

답변

2

어쩌면 SetSource이 MemoryStream을하지만 링크를 읽지 않습니다 'catastropic 실패'이고 나중에 BitmapSource는의 실버 이미지를 얻기 위해 MemoryStream을을 사용하고 싶어하지만, 때문에 당신이 사용하는이 이미 사용하는 경우 폐기되었으며 더 이상 유효하지 않습니다.

+0

데이터가 중복 될 수 있습니다. 보이는 괜찮아 - 거기에 데이터를 처분 할 수있는 곳을 볼 수 없어요 – Yanshof

+1

당신이 사용 영역을 벗어날 때 그것은 암시 적으로'ms.Dispose()'를 호출합니다. 그것이'사용'을위한 것입니다. 그러나 당신의 예외가 그 안에서 발생하기 때문에, 이것은 내가 추측하는 대답이 아닙니다. – ZoolWay

관련 문제