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

位图调整大小,只裁剪图像,不调整大小

  •  0
  • Mario  · 技术社区  · 13 年前

    我有这个代码来调整位图的大小,但它所做的只是裁剪它,而不是调整大小,我做错了什么?

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Image image, int width, int height)
        {
            //a holder for the result
            Bitmap result = new Bitmap(width, height);
            // set the resolutions the same to avoid cropping due to resolution differences
            result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
    
            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    
                //draw the image into the target bitmap
                graphics.DrawImage(image, 0, 0, result.Width, result.Height);
            }
    
            //return the resulting bitmap
            return result;
        }
    

    我这样调用函数

    bmPhoto = Imaging.ImageProcessing.ResizeImage(bmPhoto, scaledSize.Width, scaledSize.Height);
    
    2 回复  |  直到 13 年前
        1
  •  1
  •   Abdul Saleem k dimitrov    13 年前
    // Keeping Aspect Ratio
    Image resizeImg(Image img, int width)
    {                              
        double targetHeight = Convert.ToDouble(width) / (img.Width / img.Height);
    
        Bitmap bmp = new Bitmap(width, (int)targetHeight);
        Graphics grp = Graphics.FromImage(bmp);
        grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
        return (Image)bmp;
    
    }
    
    
    // Without Keeping Aspect Ratio
    Image resizeImg(Image img, int width, int height)
    {                                   
        Bitmap bmp = new Bitmap(width, height);
        Graphics grp = Graphics.FromImage(bmp);
        grp.DrawImage(img, new Rectangle(0, 0, bmp.Width, bmp.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
        return (Image)bmp;
    
    }
    
        2
  •  1
  •   Maloric    13 年前

    尝试使用 Rectangle 对象,以指定要填充的新图像部分,如下所示:

    graphics.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height), 0,  0, image.Width, image.Height, GraphicsUnit.Pixel, null);
    

    如前所述 长方形 指定图像应绘制在左上角和右下角之间,然后提供要缩放到该区域的原始图像的坐标( 0,0,image.Width,image.Height ).