Search code examples
c#asp.netimage-processinggdi

gdi+ error saving image from console application


I know this question has been answered earlier but somehow I cannot resolve the issue from the available solutions.

using (var stream = new FileStream(@"D:\test\6.png", FileMode.Open))
                { 
                    var path = @"D:\test1\";
                    using (var image = Image.FromStream(stream))
                    {
                        var newWidth = (int)(image.Width * 0.5);
                        var newHeight = (int)(image.Height * 0.5);
                        var thumbnailImg = new Bitmap(newWidth, newHeight);
                        var thumbGraph = Graphics.FromImage(thumbnailImg);
                        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                        thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                        thumbGraph.DrawImage(image, imageRectangle);
                        thumbnailImg.Save(path, image.RawFormat);
                    }
            }

When I run the following code I get an error as

An unhandled exception of type 'System.Runtime.InteropServices.ExternalException' occurred in System.Drawing.dll

Additional information: A generic error occurred in GDI+.


Solution

  • The path variable does not point to an actual filename and just a folder name. That is your problem. :)

    If you change it to

     var path = @"D:\test1\newImage.bmp";
    

    or similar it should work. (change the extension into something that matches your output image format)