缩放System.Drawing.Bitmap给定的尺寸,同时保持高宽比 [英] Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

查看:1126
本文介绍了缩放System.Drawing.Bitmap给定的尺寸,同时保持高宽比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想缩放 System.Drawing.Bitmap 来至少比一些固定的宽度和高度。这是生成缩略图网站上的图片库,所以我想保持纵横比不变。

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 I want to keep the aspect ratio the same.

我有一些跨越了不少解决方案,但似乎没有真正做什么,我需要的;它们围绕缩放基于保持的宽度或高度相同的,但不改变两者。

I have some across quite a few solutions but none seem to really do what I need; they revolve around scaling based on keeping the width or the height the same but not changing both.

一个例子:

如果我有4272由2848的图像,我想将它扩展到一个大小为1024×768,然后将得到的形象应该是1024 683和填充(带黑色边框)为1024×768。

If I have a 4272 by 2848 image and I want to scale it to a size of 1024 by 768, then the resulting image should be 1024 by 683 and padded (with a black border) to 1024 by 768.

我怎样才能做到这一点比所需大小,比要求的大小和还盘图像更小的图像不出来我需要一次规模的确切大小?

How can I do this with images larger than the required size and smaller than the require sized and also pad images which don't come out to the exact size I need once scaled?

推荐答案

目标参数:

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

您原始文件:

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, new Rectangle(((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight));

不要忘了做一个 bmp.Save(文件名)来保存生成的文件。

这篇关于缩放System.Drawing.Bitmap给定的尺寸,同时保持高宽比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆