[英]What's the best way to “square” an image in .NET?
I need generate thumbnails for a bunch of jpegs (200,000+) but I want to make sure all of my thumbs have a equal height and width. 我需要为一堆jpeg(200,000+)生成缩略图 ,但是我想确保所有拇指的高度和宽度均相等。 However, I don't want to change the proportions of the image so I need to add empty space to the shorter dimension to "square it up". 但是,我不想更改图像的比例,因此需要在较短的尺寸上添加空白空间以“将其平方”。 The empty space's background color is variable. 空白区域的背景颜色是可变的。
Here's the code snippet I'm using to generate the thumbs. 这是我用来生成缩略图的代码段。 What's the best way to do the squaring? 进行平方的最佳方法是什么?
Dim imgDest As System.Drawing.Bitmap = New Bitmap(ScaleWidth, ScaleHeight)
imgDest.SetResolution(TARGET_RESOLUTION, TARGET_RESOLUTION)
Dim grDest As Graphics = Graphics.FromImage(imgDest)
grDest.DrawImage(SourceImage, 0, 0, imgDest.Width, imgDest.Height)
How about this. 这个怎么样。 Maybe you should draw a black (or whichever color) rectangle on the Bitmap first. 也许您应该先在位图上绘制一个黑色(或任何颜色)矩形。
And then when you are placing the resized image, just calculate the placement of the image based on whichever dimension is shorter, and then move that dimension by half the difference (and keep the other on 0). 然后,当您放置调整大小后的图像时,只需根据较小的尺寸计算图像的位置,然后将该尺寸移动一半的差值(另一个保持为0)。
Wouldn't that work? 那行不通吗?
Like Vaibhav said, first paint the entire thumbnail area with black. 就像Vaibhav所说的那样,首先用黑色绘制整个缩略图区域。 This will be simpler than first fitting the image into the thumbnail and then determining which rectangles to paint black to achieve pillarboxing or letterboxing . 这将比先将图像适合缩略图,然后确定要涂成黑色的矩形来实现立柱装箱或信箱 装填要简单得多。
Pseudo-code for a general solution to fit an imageWidth
x imageHeight
image into a thumbWidth
x thumbHeight
(doesn't have to be a square) area: 用于将imageWidth
x imageHeight
图像适配到thumbWidth
x thumbHeight
(不必是正方形)区域的一般解决方案的伪代码:
imageRatio = imageWidth / imageHeight;
thumbRatio = thumbWidth / thumbHeight;
zoomFactor = imageRatio >= thumbRatio
? thumbWidth / imageWidth
: thumbHeight / imageHeight;
destWidth = imageWidth * zoomFactor;
destHeight = imageHeight * zoomFactor;
drawImage(
(thumbWidth - destWidth) >> 1,
(thumbHeight - destHeight) >> 1,
destWidth,
destHeight);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.