-1

I want resize an Image for fit a size (width and height) without stretch the original image.

enter image description here

My code, resize the image to the specified size but stretch the original image.

enter image description here

this is the code:

public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.Tile);
            graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}
3
  • 1
    The answer is in your title: you need to scale, not resize, the image: Reduce/Increase the H or W by a percent so it fits the new size Feb 6, 2018 at 16:22
  • @Plutonix ok, but i'm here because i don't know how do it!
    – ar099968
    Feb 6, 2018 at 16:28
  • I get that. For the first, horiz one, you need to increase the size so the width matches the target width. You want to size up from 276 to about 340 or 123%. That will leave a lot of extra vertical image which gets cropped. For the other, scale based on the vertical Feb 6, 2018 at 16:43

1 Answer 1

4

So you want to Scale with respect to Aspect Ratio.

What we should do is to get a factor and resize both width and height by that factor.
And we need not to go above desired width and height (that's why we use Math.Min on both width and height ratios).

double oldWidth = image.Width;
double oldHeight = image.Height;

var widthRatio = width / oldWidth;
var heightRatio = height / oldHeight;

var factor = Math.Min(widthRatio, heightRatio);

and here we use it like this:

var destRect = new Rectangle(0, 0, (int)(factor * oldWidth), (int)(factor * oldHeight));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.