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

C#运行时调整图片大小:修复保存缩放后图片而非原图的问题

修复方案

你的问题出在代码缺少判断原图尺寸是否超过阈值的逻辑,且未区分“需要缩放”和“直接保存原图”的处理分支。以下是修复后的代码,实现仅当原图宽度>1024或高度>768时才进行缩放,否则直接保存原图:

private static void ResizeImageIfNeeded(int maxWidth, int maxHeight, Stream originalImageStream, string targetPath)
{
    using (var image = System.Drawing.Image.FromStream(originalImageStream))
    {
        // 判断原图是否超过指定尺寸阈值
        bool needResize = image.Width > maxWidth || image.Height > maxHeight;

        if (needResize)
        {
            // 计算等比例缩放后的尺寸(若不需要等比例,可替换为你指定的固定宽高)
            float ratio = Math.Min((float)maxWidth / image.Width, (float)maxHeight / image.Height);
            int newWidth = (int)(image.Width * ratio);
            int newHeight = (int)(image.Height * ratio);

            // 创建缩放后的位图并绘制
            using (var thumbnailImg = new Bitmap(newWidth, newHeight))
            using (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(targetPath, image.RawFormat);
            }
        }
        else
        {
            // 原图尺寸符合要求,直接保存原图
            image.Save(targetPath, image.RawFormat);
        }
    }
}

关键修改点

  • 新增needResize判断逻辑,仅在原图尺寸超限时执行缩放操作
  • 加入等比例缩放计算(若需固定宽高,可替换为传入的指定参数)
  • 用嵌套using块确保Bitmap和Graphics资源被正确释放
  • 分分支处理:缩放后保存新图 / 直接保存原图

使用示例

调用时传入阈值1024和768即可:

ResizeImageIfNeeded(1024, 768, originalImageStream, targetFilePath);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:41:07