为什么要创建一个新的Bitmap转换为BitmapImage?

时间:2015-09-02 00:29:31

标签: wpf bitmap valueconverter

我在一些遗留代码中有一个转换器,它做了一些看似错误的事情,但我不太了解位图。 看起来它基于https://stackoverflow.com/a/3427114/57883 有一些附加功能。

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace CompanyName.Converters
{
    [ValueConversion(typeof(System.Drawing.Image), typeof(System.Windows.Media.ImageSource))]

    /// <summary>
    /// One-way converter from System.Drawing.Image to System.Windows.Media.ImageSource
    /// </summary>
    public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // empty images are empty...
            if (value == null) 
            { 
                return null; 
            }

            if (value.GetType() == typeof(System.Drawing.Image))
            {
                var image = (System.Drawing.Image)value;

            // Winforms Image we want to get the WPF Image from...
            var bitmap = new System.Windows.Media.Imaging.BitmapImage();
            bitmap.BeginInit();
            MemoryStream memoryStream = new MemoryStream();

            // Save to a memory stream...
            image.Save(memoryStream, ImageFormat.Bmp);

            // Rewind the stream...
            memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
            bitmap.StreamSource = memoryStream;
            bitmap.EndInit();
            bitmap.Freeze();
            return bitmap;
            }

            else if (value.GetType() == typeof(System.Drawing.Bitmap))
            {
                var image = value as System.Drawing.Bitmap;

                System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

                using (MemoryStream memory = new MemoryStream())
                {
                    bitmap.Save(memory, ImageFormat.Png);
                    memory.Position = 0;
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = memory;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                    bitmapImage.Freeze();
                    return bitmapImage;
                }
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

为什么世界会System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);?这不仅仅是在内存中创建位图副本而没有任何好处吗?这只是可怕的代码还是在转换位图之前复制位图有合理的理由吗?

1 个答案:

答案 0 :(得分:1)

通过构造函数复制位图而不显式指定PixelFormat将导致图像转换为32bpp argb,这将防止出现问题,如果您尝试绑定到目标不具有像素格式的图像支持。在WPF的情况下,Image控件确实正确呈现索引图像,但可能有其他格式或其他控件类型将失败。原作者可能只是试图涵盖所有基础。