您的位置:首页 > 编程语言

图片适应pictureBox大小显示代码

2013-01-10 14:22 239 查看
#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(指定高质量的双线性插值法。执行预筛选以确保高质量的收缩)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: