2016-04-11 70 views
1

我有一個數據庫程序,它將圖像存儲到SQL DB中,並將其讀回到WPF應用程序中顯示。如果我使用Jpeg圖像,它工作正常,但如果我使用PNG圖像,我想用它來保持透明度(存儲時會消失),但大多數圖像都會損壞。當從SQL回讀時PNG文件已損壞

這是已被選定

enter image description here

我然後將其保存到數據庫,並添加圖像列表視圖

enter image description here

然後,如果我關閉應用程序的圖像並重新加載它,它從數據庫拉回圖像,你可以看到它在列表視圖中已損壞

enter image description here

,然後當我選擇它,則圖像控制還示出了損壞的圖像

enter image description here

我使用的是的BitmapImage對象存儲在代碼的圖像,並且使用該設置圖像。源,並將其轉換爲字節[]以存儲到數據庫中的圖像字段中。

i中的BitmapImage轉換爲字節[]使用以下行

    command.Parameters.AddWithValue("@Image", ImageToByteArray(productImage.ProductImage)); 

並且這些轉換,並從一個BitmapImage的

 private static BitmapImage BuildImage(byte[] image) 
    { 
     var bitmap = new BitmapImage(); 
     bitmap.BeginInit(); 
     MemoryStream mem = new MemoryStream(image); 
     bitmap.StreamSource = mem; 
     bitmap.CacheOption = BitmapCacheOption.OnLoad; 
     bitmap.EndInit(); 
     //bitmap.Freeze(); 

     return bitmap; 
    } 

    private static byte[] ImageToByteArray(BitmapImage image) 
    { 
     byte[] data; 
     JpegBitmapEncoder encoder = new JpegBitmapEncoder(); 
     encoder.Frames.Add(BitmapFrame.Create(image)); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      encoder.Save(ms); 
      data = ms.ToArray(); 
     } 

     return data; 

    } 

正常工作與JPEG文件的功能,但隨後我有圖像的白色背景。

任何幫助將不勝感激。

+0

您使用哪種編程語言和DBMS? –

+0

我建議在SQL中使用varBinary作爲數據類型,並將其放入C#中的流中並將其轉換爲字符串base64;) –

+0

圖像僅僅是SQL Server的BLOB。它不會以任何方式影響或修改數據,所以問題在於您如何存儲和讀取它... – gbn

回答

1

作爲個人喜好,我會將您的SQL數據列更改爲varbinary(MAX),並使用stream和BinaryReader對象上傳文件。

但我認爲你的問題是你沒有使用PNG的PngBitmapEncoder,你正在使用JpegBitmapEncoder而不考慮文件類型。

希望這會有所幫助。