图像转换器不工作

时间:2017-07-24 20:23:25

标签: c# bitmapimage ivalueconverter

任何人都可以解释我收到错误的原因:

  

GDI +中发生了一般错误

以下是代码:

[ValueConversion(typeof(System.Drawing.Image), typeof(ImageSource))]
public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;

        System.Drawing.Image img = (System.Drawing.Image)value;
        BitmapImage bitmap = new BitmapImage();

        using (MemoryStream ms = new MemoryStream())
        {
            img.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);

            bitmap.BeginInit();
            bitmap.StreamSource = ms;
            bitmap.EndInit();
        }
        return bitmap;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

它在img.Save(ms, ImageFormat.Bmp)行打破了。

谢谢。

1 个答案:

答案 0 :(得分:0)

如果Save方法失败,您应该查看传递给方法的源图像。你如何加载/创建这个图像?也许图像已被处理或其内部流已关闭?

请参阅此问题及其接受的答案:Image.Save(..) throws a GDI+ exception because the memory stream is closed