簡體   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