在流中保存图像时,GDI +中发生了一般错误

时间:2013-12-05 14:22:34

标签: c# asp.net .net gdi+

这是我试图实现的目标:

  • 将png图片上传到服务器
  • 保存;
  • 加载保存的图像,生成缩略图;
  • 将其保存在不同的位置;

一切都很好,直到我必须保存缩略图。起初我认为它是文件夹权限或其他东西,所以要验证我试图将其保存在MemmoryStream中,并再次得到这个“通用GDI +错误”,没有InnerException或一些描述性StackTrace。 我在想与处理原始Bitmap有关但仍然相同。这是代码:

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;
}

我不知道还有什么可以帮助。

1 个答案:

答案 0 :(得分:0)

感谢所有对我的问题发表评论的人,你的评论引导我找到了正确的问题。

所以这行代码是错误的:Image thumb = image.GetThumbnailImage(thumbsWidth, thumbsHeight, AbortThumbnailPicture, IntPtr.Zero);

现在我正在使用更加标准化的代码来完成工作,这里是:

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;
    }