Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

前端 未结 3 637
慢半拍i
慢半拍i 2020-11-28 08:35

I want to scale a System.Drawing.Bitmap to at least less than some fixed width and height. This is to generate thumbnails for an image gallery on a website, so

3条回答
  •  野性不改
    2020-11-28 09:14

    Target parameters:

    float width = 1024;
    float height = 768;
    var brush = new SolidBrush(Color.Black);
    

    Your original file:

    var image = new Bitmap(file);
    

    Target sizing (scale factor):

    float scale = Math.Min(width / image.Width, height / image.Height);
    

    The resize including brushing canvas first:

    var bmp = new Bitmap((int)width, (int)height);
    var graph = Graphics.FromImage(bmp);
    
    // uncomment for higher quality output
    //graph.InterpolationMode = InterpolationMode.High;
    //graph.CompositingQuality = CompositingQuality.HighQuality;
    //graph.SmoothingMode = SmoothingMode.AntiAlias;
    
    var scaleWidth = (int)(image.Width * scale);
    var scaleHeight = (int)(image.Height * scale);
    
    graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
    graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
    

    And don't forget to do a bmp.Save(filename) to save the resulting file.

提交回复
热议问题