Here is the thing I try to achieve:

  • Upload png image to server
  • Save it;
  • Load the saved image, generate thumbnail;
  • Save it in different location;

Everything is fine until I have to save the thumbnail. At first I thought that it is the folder permissions or something, so to verify I tried to save it in a MemmoryStream and again I get this "generic GDI+ error", no InnerException or some descriptive StackTrace. I was thinking that there is something to do with disposing the original Bitmap but still the same. Here is the code:

postedFile.SaveAs(fullFilePath);
FileStream fs = new FileStream(fullFilePath, FileMode.Open);
Image image = Bitmap.FromStream(fs);

Image thumb = image.GetThumbnailImage(thumbsWidth, thumbsHeight, AbortThumbnailPicture, IntPtr.Zero);
image.Dispose();
fs.Dispose();
using (MemoryStream ms = new MemoryStream())
{
    thumb.Save(ms, ImageFormat.Png); //*** HERE THROWS THE EXCEPTION ***

    using (FileStream fstream = new FileStream(fullThumbsPath, FileMode.Create, FileAccess.Write))
    {
        ms.WriteTo(fstream);
        fstream.Close();
    }
    ms.Close();
}

// The GetThumbnailImage callback
private bool AbortThumbnailPicture()
{
    return true;
}

I don't know what else to do please help.

有帮助吗?

解决方案

Thank all of you that commented on my question, your comments lead me to the right problem.

So this line of code is just wrong: Image thumb = image.GetThumbnailImage(thumbsWidth, thumbsHeight, AbortThumbnailPicture, IntPtr.Zero);

Now I'm using more standardized code that gets the job done very well, here it is:

public static Image ResizeImage(Image image, Size size, bool preserveAspectRatio = true)
    {
        int newWidth;
        int newHeight;
        if (preserveAspectRatio)
        {
            var originalWidth = image.Width;
            var originalHeight = image.Height;
            var percentWidth = size.Width / (float)originalWidth;
            var percentHeight = size.Height / (float)originalHeight;
            var percent = percentHeight < percentWidth ? percentHeight : percentWidth;
            newWidth = (int)(originalWidth * percent);
            newHeight = (int)(originalHeight * percent);
        }
        else
        {
            newWidth = size.Width;
            newHeight = size.Height;
        }
        Image newImage = new Bitmap(newWidth, newHeight);
        using (var graphicsHandle = Graphics.FromImage(newImage))
        {
            graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicsHandle.SmoothingMode = SmoothingMode.HighQuality;
            graphicsHandle.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphicsHandle.DrawImage(image, 0, 0, newWidth, newHeight);
        }
        return newImage;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top