图片适应pictureBox大小显示代码

本文介绍了一种在图片框中显示相应大小图片的方法,包括如何调整图片大小以适应不同尺寸的图片框,并提供了相应的代码实现。通过比较图片宽度与图片框宽度,确保图片在显示时不被拉伸或变形,同时利用高质量的双线性插补方法来提高图片缩放效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#region 在图片框中显示相应大小的图片
        private Bitmap ResizeImage(Bitmap bmp, PictureBox picBox)
        {
            float xRate = (float)bmp.Width / picBox.Size.Width;//比较picBox的宽度与图片本身的宽度
            float yRate = (float)bmp.Height / picBox.Size.Height;
            if (xRate <= 1 && yRate <= 1)//图片比picBox小
            {
                return bmp;//返回
            }


            else
            {
                float tRate = (xRate >= yRate) ? xRate : yRate;
                Graphics g = null;
                try
                {
                    int newW = (int)(bmp.Width / tRate);
                    int newH = (int)(bmp.Height / tRate);
                    Bitmap b = new Bitmap(newW, newH);
                    g = Graphics.FromImage(b);
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                    g.Dispose();
                    //bmp.Dispose();
                    return b;
                }
                catch
                {
                    //bmp.Dispose();
                    return null;
                }
                finally
                {
                    if (null != g)
                    {
                        g.Dispose();
                    }
                }
            }
        }
        #endregion
        
#region 上传本地图片并预览
        private void btn_preview_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdlg = new OpenFileDialog();
            ofdlg.Title = "选择上传的图片";
            ofdlg.Filter = "All Files(*.*)|*.*|位图(*.bmp)|*.bmp|JPEG(*.jpg)|*.jpg";
            ofdlg.ShowDialog();//显示文件对话框
            txt_ImgPath.Text = ofdlg.FileName;//获取文件名并填充在文件路径文本框
            if (File.Exists(ofdlg.FileName))//判断文件是否存在
            {
                Bitmap bmp = new Bitmap(ofdlg.FileName);
                Bitmap Pic = ResizeImage(bmp,pictureBox_nowpic);//调用调整大小函数
                pictureBox_nowpic.Image = Pic;
            }


            else
            {
                MessageBox.Show(this, "图片为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        #endregion


备注:
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
设置图片与 g 关联的插补模式为InterpolationMode.HighQualityBicubic(指定高质量的双线性插值法。执行预筛选以确保高质量的收缩)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RonTech

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值