-1

Can anyone explain why I am getting the error:

A generic error occurred in GDI+

Here is the code:

[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();
    }
}

It is breaking on the img.Save(ms, ImageFormat.Bmp) line.

Thank you.

g.b
  • 85
  • 3
  • Instead of saving to a stream, do so to a file. Does that still throw the same error? If not, can you open said file with an image viewer? – Trey Jul 24 '17 at 20:46

1 Answers1

0

If the Save method fails you should look at your source image that you pass to the method. How do you load/create this image? Maybe the image is already disposed or its internal stream was closed?

See this question and its accepted answer: Image.Save(..) throws a GDI+ exception because the memory stream is closed

Robert S.
  • 1,942
  • 16
  • 22