在 PictureBox Form C# 中调整大小时丢失图像质量

Posted

技术标签:

【中文标题】在 PictureBox Form C# 中调整大小时丢失图像质量【英文标题】:Losing image quality when resize in PictureBox Form C# 【发布时间】:2021-09-20 01:36:13 【问题描述】:

我有一个没有边框的表单,只需要在窗口角落显示一个图像,图片尺寸为 9567 x 18012,大小为 62 MB,我在调整质量损失时在表单中使用 PictureBox,为什么?,我需要第三方库来显示尺寸和尺寸都很大的图像吗?

左图是带有我的图像的PictureBox,右图是带有te信息的原始图像

【问题讨论】:

【参考方案1】:

使用以下代码缩小图片尺寸。

public void SetPictureBoxImage(string path)

    Image myImage = Image.FromFile(path, true);
    int width = 500;
    double ratio = (double)myImage.Width / (double)myImage.Height;
    int height = Convert.ToInt32(width / ratio);
           
    if (height > width)
    
        ratio = (double)myImage.Height / (double)myImage.Width;
        height = width;
        width = Convert.ToInt32(height / ratio);
    
    pictureBox1.Image = ResizeImage(myImage, width, height);

调整大小方法

public static Bitmap ResizeImage(Image image, int width, int height)

   var destRect = new Rectangle(0, 0, width, height);
   var destImage = new Bitmap(width, height);

   destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
   using (var graphics = Graphics.FromImage(destImage))
   
      graphics.CompositingMode = CompositingMode.SourceCopy;
      graphics.CompositingQuality = CompositingQuality.HighQuality;
      graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
      graphics.SmoothingMode = SmoothingMode.HighQuality;
      graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

      using (var wrapMode = new ImageAttributes())
      
          wrapMode.SetWrapMode(WrapMode.TileFlipXY);
          graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
      
   

   return destImage;

【讨论】:

以上是关于在 PictureBox Form C# 中调整大小时丢失图像质量的主要内容,如果未能解决你的问题,请参考以下文章

C# WinForm应用程序,PictureBox控件透明效果的相关问题。

c#在panel中动态增加控件时怎样自动调整panel的行列大小

在c#中如何对picturebox设置一个滚动条啊

C# winform开发中用picturebox 只能显示大图片一部分,如何生成适合picturebox的图片并且保证不失真?有知

c# 打印里图片这么让png的高清大图按比例缩小,

C# 制作(PictureBox)圆形头像框 从数据库中读取头像