【问题标题】:WPF BitmapFrame to BitmapImageWPF BitmapFrame 到 BitmapImage
【发布时间】:2018-11-26 22:46:40
【问题描述】:

我有一个来自反序列化的 BitmapFrame。我需要将其转换为 BitmapImage。怎么做? 我使用了这段代码:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/31808363-6b00-43dd-8ea8-0917a35d62ad/how-to-convert-stream-to-bitmapsource-and-how-to-convert-bitmapimage-to-bitmapsource-in-wpf?forum=wpf

问题是 BitmapImage 没有 Source 属性,只有 StreamSource 或 UriSource。

序列化部分:

public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            MemoryStream stream = new MemoryStream();
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(image.UriSource));
            encoder.QualityLevel = 30;
            encoder.Save(stream);
            stream.Flush();
            info.AddValue("Image", stream.ToArray());
...

反序列化:

public ImageInfo(SerializationInfo info, StreamingContext context)
        {
            //Deserialization Constructorbyte[] encodedimage = (byte[])info.GetValue("Image", typeof(byte[]));
            if (encodedimage != null)
            {
                MemoryStream stream = new MemoryStream(encodedimage);
                JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
                Image = new BitmapImage();
                Image.BeginInit();
                //Image.StreamSource = ...  decoder.Frames[0];
                Image.EndInit();
                Image.Freeze();
            }
...

我需要一些有效的东西来代替上面的评论......

【问题讨论】:

    标签: wpf bitmap bitmapimage


    【解决方案1】:

    除了您实际上并不需要这种转换(因为您可以在使用 BitmapImage 的任何地方使用 BitmapFrame)之外,您还可以直接从字节数组中的编码位图解码 BitmapImage。

    不必显式使用 BitmapDecoder。当您将 Stream 分配给 BitmapImage 的 StreamSource 属性时,框架会自动使用适当的解码器。在创建 BitmapImage 后应立即关闭 Stream 时,您必须注意设置 BitmapCacheOption.OnLoad

    Image = new BitmapImage();
    using (var stream = new MemoryStream(encodedimage))
    {
        Image.BeginInit();
        Image.CacheOption = BitmapCacheOption.OnLoad;
        Image.StreamSource = stream;
        Image.EndInit();
    }
    Image.Freeze();
    

    【讨论】:

    • 谢谢,效果很好!顺便说一句,当我使用上述 GetObjectData 方法序列化图像时,我得到大约 300-400KB / 图像(序列化)。所有图像的宽度最多为 150 像素(比例为 4:3 或 16:9),质量级别 = 30。我认为这相当大,我错了吗?
    • 这对于 150x100 左右的像素来说太过分了。它应该只有几 KB。您确定要测量编码字节数组的大小吗?它会随着 QualityLevel 的降低而降低吗?
    • 哎呀,我已经对图像的 UriSource 进行了编码,所以是全尺寸图像而不是 150x... 缩略图。现在是 5-7KB/图像 :) 再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多