图片适应pictureBox大小显示代码

来源:互联网 发布:淘宝开店流量是什么 编辑:程序博客网 时间:2024/06/16 15:05
#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(指定高质量的双线性插值法。执行预筛选以确保高质量的收缩)。
原创粉丝点击