2016-09-16 65 views
0

我需要將BitmapImage轉換爲byte[],這樣我才能將這些數據存儲在SQLite數據庫中,而相反地加載它。在UWP中將BitmapImage轉換爲byte [],然後在sqlite中插入

我的XAML有一個形象:

<Image x:Name="image" HorizontalAlignment="Left" Height="254" Margin="50,117,0,0" VerticalAlignment="Top" Width="244" Source="Assets/LockScreenLogo.png"/>

我的C#代碼:

public sealed partial class MainPage : Page 
{ 
    public MainPage() 
    { 
     this.InitializeComponent(); 
     BitmapImage test = new BitmapImage(); 
     test = (BitmapImage)image.Source; 
     image.Source = test; 

     byte[] array = ImageToByte(test); 
     Database.CreateDB(); 
     Database.InsertData(array); 
    } 



    #region convert 
    public byte[] ImageToByte(BitmapImage image) 
    { 

     //WriteableBitmap wb; 
     using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream()) 
     { 
      image.SetSource(ms); 

      WriteableBitmap wb = new WriteableBitmap(244, 254); 
      wb.SetSource(ms); 

      using (Stream stream = wb.PixelBuffer.AsStream()) 
      using (MemoryStream memoryStream = new MemoryStream()) 
      { 
       stream.CopyTo(memoryStream); 
       return memoryStream.ToArray(); 
      } 
     } 
    } 

    public BitmapImage ByteToImage(byte[] array) 
    { 
     BitmapImage image = new BitmapImage(); 
     using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream()) 
     { 
      stream.AsStreamForWrite().Write(array, 0, array.Length); 
      stream.Seek(0); 
      image.SetSource(stream); 
     } 
     return image; 
    } 
    #endregion 

} 

這是行不通的。

異常消息:

「類型‘System.ArgumentNullException’的一個例外發生在mscorlib.ni.dll但在用戶代碼中沒有處理

其他信息:值不能爲空。」

有人可以幫助我嗎?

+0

[在UWP中將BitmapImage轉換爲字節數組]可能的副本(http://stackoverflow.com/questions/36108056/convert-a-bitmapimage-to-byte-array-in-uwp) – Clemens

回答

0

不幸的是,這是不可能的,除非你有圖像的延遲源(如StorageItem或URL)。

要訪問像素(然後進行任何處理),您需要一個WriteableBitmap對象而不是BitmapImage

相關問題