【问题标题】:Converting BitmapImage to byte[] in UWP and insert in sqlite在 UWP 中将 BitmapImage 转换为 byte[] 并插入到 sqlite
【发布时间】:2016-09-16 18:16:46
【问题描述】:

我需要将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

}

这不起作用。

异常信息:

“在 mscorlib.ni.dll 中发生了“System.ArgumentNullException”类型的异常,但未在用户代码中处理

附加信息:值不能为空。”

有人可以帮助我吗?

【问题讨论】:

标签: c# sqlite bitmap uwp data-conversion


【解决方案1】:

很遗憾,除非您有图像的无延迟源(如 StorageItem 或 URL),否则这是不可能的。

要访问像素(并在之后进行任何处理),您需要一个 WriteableBitmap 对象而不是 BitmapImage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多