图片自适应pictureBox的大小显示

#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

 

posted @ 2020-11-30 17:29  ₯㎕~  阅读(450)  评论(0编辑  收藏  举报