问题描述
我想将 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 x 2848 的图像并且我想将其缩放到 1024 x 768 的大小,那么生成的图像应该是 1024 x 683 并填充(带有黑色边框)到 1024 x 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, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
并且不要忘记执行 bmp.Save(filename)
来保存生成的文件.
And don't forget to do a bmp.Save(filename)
to save the resulting file.
这篇关于将 System.Drawing.Bitmap 缩放到给定大小,同时保持纵横比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!