繁体   English   中英

调整图像大小以保持宽高比白线边框

[英]Resize Image Keep Aspect Ratio White Line Border

我使用以下代码(从此处的示例2进行改编)来调整图像的大小,以保持宽高比。但是我在调​​整大小后的图像周围始终出现白色边框。我在做什么错。

 Bitmap ResizekeepAspectRatio(Bitmap imgPhoto, int Width, int Height)
            {
                int sourceWidth = imgPhoto.Width;
                int sourceHeight = imgPhoto.Height;
                int sourceX = 0;
                int sourceY = 0;
                int destX = 0;
                int destY = 0;

                float nPercent = 0;
                float nPercentW = 0;
                float nPercentH = 0;

                nPercentW = ((float)Width / (float)sourceWidth);
                nPercentH = ((float)Height / (float)sourceHeight);
                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentH;
                    destX = System.Convert.ToInt16((Width -
                                  (sourceWidth * nPercent)) / 2);
                }
                else
                {
                    nPercent = nPercentW;
                    destY = System.Convert.ToInt16((Height -
                                  (sourceHeight * nPercent)) / 2);
                }

                int destWidth = (int)(sourceWidth * nPercent);
                int destHeight = (int)(sourceHeight * nPercent);

                Bitmap bmPhoto = new Bitmap(Width, Height,
                                  PixelFormat.Format24bppRgb);
                bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                 imgPhoto.VerticalResolution);

                Graphics grPhoto = Graphics.FromImage(bmPhoto);
                grPhoto.Clear(Color.White);
                grPhoto.InterpolationMode =
                        InterpolationMode.HighQualityBicubic;

                grPhoto.DrawImage(imgPhoto,
                    new Rectangle(destX, destY, destWidth, destHeight),
                    new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                    GraphicsUnit.Pixel);

                grPhoto.Dispose();
                return bmPhoto;
            }

更新:

样本大小调整后的图像

在此处输入图片说明

放大角落显示白色边框

在此处输入图片说明

尝试换线

Bitmap bmPhoto = new Bitmap(Width, Height,
                              PixelFormat.Format24bppRgb);
To 
 Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
                          PixelFormat.Format24bppRgb);

由于您大多数时候都想保持宽高比,因此最终会在图像周围留有额外的空间,因此,如果您不需要这些额外的空间,请使新图片的尺寸适合新的目标尺寸

编辑:

Try to comment out the line grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM