代码之家  ›  专栏  ›  技术社区  ›  techno

调整图像大小保持纵横比白线边框

  •  0
  • techno  · 技术社区  · 9 年前

    Example #2 here )以保持纵横比调整图像大小。但我一直在调整大小的图像周围添加白色边框。我做错了什么。

     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;
                }
    

    更新:

    调整大小后的图像示例

    enter image description here

    缩放 角内分隔缝白色边框

    enter image description here

    1 回复  |  直到 9 年前
        1
  •  1
  •   Aladin Hdabe    9 年前

    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