You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GDI+通用错误排查:图片缩放保存时抛出ExternalException问题

GDI+通用错误原因分析与修复

错误核心原因

  • 图像被Graphics对象锁定时执行保存:你在第二个using (Graphics graphics = Graphics.FromImage(resizedImage))块内调用resizedImage.Save(),此时Graphics对象仍持有该Bitmap的资源锁,GDI+不允许在图像处于锁定状态时执行保存操作,这是触发异常的直接原因。
  • 冗余的Graphics对象创建:第一个using块创建Graphics并设置画质参数后就释放了,第二个重新创建的Graphics并未继承这些设置,导致你配置的高质量缩放参数完全无效,属于无效代码。
  • 资源释放不严谨:originalImage和resizedImage未用using块包裹,若中间代码抛出异常,Dispose方法不会执行,可能导致GDI+资源泄漏,间接引发异常。

修复后的代码

private void ImageProcessingAndSaving(string imagePath, string exportPath)
{
    // 用using包裹Bitmap,确保资源自动释放
    using (Bitmap originalImage = new Bitmap(imagePath))
    {
        int desiredWidth = 600;
        int desiredHeight = 600;
        
        using (Bitmap resizedImage = new Bitmap(desiredWidth, desiredHeight))
        {
            resizedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
            
            // 单个Graphics对象完成参数设置、绘图、释放,避免锁定冲突
            using (Graphics graphics = Graphics.FromImage(resizedImage))
            {
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                
                // 执行缩放绘图
                graphics.DrawImage(originalImage, 0, 0, desiredWidth, desiredHeight);
            }
            
            // Graphics已释放,此时保存无锁定冲突
            resizedImage.Save(exportPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

额外注意事项

  • 确保exportPath对应的目录存在,若目录不存在,Save操作也会触发GDI+异常。
  • 若目标文件已被其他进程占用,同样会引发该异常,需检查文件是否被锁定。

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 00:57:47