【问题标题】:Convert BitmapImage or IRandomAccessStream to byte array in Windows 10 UAP在 Windows 10 UAP 中将 BitmapImage 或 IRandomAccessStream 转换为字节数组
【发布时间】:2016-04-07 12:30:15
【问题描述】:

谁能帮帮我。我不明白如何将 BitmapImage 或 IRandomAccessStream 转换为字节数组。 我试试:

foreach (StorageFile file in files)
{
    BitmapImage src = new BitmapImage();

    using (IRandomAccessStream stream = await file.OpenReadAsync())
    {
        await src.SetSourceAsync(stream);

        WriteableBitmap bitMap = new WriteableBitmap(src.PixelWidth, src.PixelHeight);
        await bitMap.SetSourceAsync(stream);
    }
}

然后我有 WriteableBitmap 并试试这个:

private byte[] ImageToByeArray(WriteableBitmap wbm)
{
    using (Stream stream = wbm.PixelBuffer.AsStream())
    using (MemoryStream memoryStream = new MemoryStream())
    {
        stream.CopyTo(memoryStream);
        return memoryStream.ToArray();
    }
}

但这对我不起作用;(

【问题讨论】:

    标签: c# bitmap windows-phone-8.1 win-universal-app bitmapimage


    【解决方案1】:

    应该这样做:

        async Task<byte[]> Convert(IRandomAccessStream s)
        {
            var dr = new DataReader(s.GetInputStreamAt(0));
            var bytes = new byte[s.Size];
            await dr.LoadAsync((uint)s.Size);
            dr.ReadBytes(bytes);
            return bytes;
        }
    

    【讨论】:

    • 等待 dr.LoadAsync((uint)s.Size);在 UWP 中无法正常工作
    【解决方案2】:

    我在我的 WPF 应用程序中使用此解决方案将数据库中的图像保存为 byte[]。它也应该适用于您的情况。

    public static byte[] ImageToString(System.Windows.Media.Imaging.BitmapImage img) {
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        System.Windows.Media.Imaging.BmpBitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder();
        encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create((System.Windows.Media.Imaging.BitmapSource)img));
        encoder.Save(stream);
        stream.Flush();
    
        return stream.ToArray();
    }
    

    【讨论】:

    • 不工作 ;(在 windows 10 uap 中没有这个类
    • 您无法导入 System.Windows.Media.Imaging 参考?
    • 这三种方案你试过了吗? Solution1 - Solution2 - Solution3
    • 是的,它也不起作用..没有类我也尝试过: var decoder = await BitmapDecoder.CreateAsync(stream); UInt32 宽度 = 解码器.PixelWidth; UInt32 高度 = 解码器.PixelHeight; var 像素 = 等待解码器.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, new BitmapTransform(), ExifOrientationMode.RespectExifOrientation, ColorManagementMode.ColorManageToSRgb);返回像素.DetachPixelData();
    • 如何获取图像? Here 如果您使用图像路径,可能的解决方案。
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多