简体   繁体   中英

C# Resize Image at runtime

I want to resize an image if size is over 1024x768 and after that save the new instance instead of the original one but this code is saving the original. how can I fix that?

      private static void ResizeImage(int newWidth, int newHeight, Stream OriginalImage, string targetPath)
    {
        using (var image = System.Drawing.Image.FromStream(OriginalImage))
        {
            var thumbnailImg = new Bitmap(newWidth, newHeight);
            var thumbGraph = Graphics.FromImage(thumbnailImg);
            thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
            thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
            thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
            thumbGraph.DrawImage(image, imageRectangle);
            thumbnailImg.Save(targetPath, image.RawFormat);
        }
    }

I'm assuming "thumbnailImg" is supposed to be downscaled version of "image".

If so - use Bitmap constructor designed exactly for this purpose:

Bitmap(Image, Int32, Int32)

For example:

var thumbnail = new Bitmap(image, newWidth, newHeight);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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