最佳尺寸调整和/或裁切逻辑 [英] Best resize and or crop logic
问题描述
我已经遇到过几次,并认为将其放到那里会很好.您最好的图像调整大小和/或裁剪逻辑是什么.想法是使用目标图像,尺寸和裁剪标记调用某些方法-这将返回或保存下来,或者返回任何所需的图像.
I've come across this a few times and thought it would be good to put it out there. What's your best image resize and/or crop logic. The idea being that some method is called with a target image, dimensions and a crop flag - this would return or save off or whatever the desired image.
我的在下面.从VB转换为C#,是的,会有一些小错误,但是逻辑是我们要关注的.
Mine is below. Converted from VB to C# so yes there'll be small bugs but logic is what we're looking at.
// INIT
// On/off
bool WeAreCropping = true;
// Get some dimensions
int TargetWidth = RequestedWidth;
int TargetHeight = RequestedHeight;
int SourceWidth = SourceImage.Width;
int SourceHeight = SourceImage.Height;
int ResizeWidth = TargetWidth;
int ResizeHeight = TargetHeight;
// GET RESIZE VALUES
// Are we cropping?
if (WeAreCropping) {
// Get source and target aspect ratio
double SourceAspectRatio = SourceWidth / SourceHeight;
double TargetAspectRatio = TargetWidth / TargetHeight;
// Compare aspect ratios to find out if we should we resize by
// width or height or nothing
if (TargetAspectRatio < SourceAspectRatio) {
ResizeWidth = TargetHeight / SourceHeight * SourceWidth;
}
else if (TargetAspectRatio > SourceAspectRatio) {
ResizeHeight = TargetWidth / SourceWidth * SourceHeight;
}
else {
// Same aspect ratio
}
}
else {
// If the target image is bigger than the source
if (TargetWidth > SourceWidth && TargetHeight > SourceHeight) {
TargetWidth = SourceWidth;
TargetHeight = SourceHeight;
}
double Ratio = 0;
// What ratio should we resize it by
if (SourceWidth / TargetWidth > SourceHeight / TargetHeight) {
Ratio = SourceWidth / TargetWidth;
}
else {
Ratio = SourceHeight / TargetHeight;
}
ResizeWidth = Math.Ceiling(SourceWidth / Ratio);
ResizeHeight = Math.Ceiling(SourceHeight / Ratio);
}
// TIME TO DO SUMFINK
// Resize the image using ResizeWidth and ResizeHeight
// Do it
if (WeAreCropping) {
// Crop the resized image at the center TargetWidth and TargetHeight
// Do it
}
我怀疑这可能会更加优雅,所以也许您可以做得更好.
I suspect this could be much more elegant so maybe you could do better.
推荐答案
我会说您应该使用标准几何类型,例如Rectangle
和Size
.那么,当调用者希望将图像放置在更大的矩形中,但仍希望保持原始图像尺寸比例时,您可能还应该支持一个用例.
I'd say you should utilize standard geometry types like Rectangle
and Size
. Then you should probably also support a use case, when the caller wants to fit the image in some larger rectangle, but still wants to keep the original image sizes ratio.
One way to implement the resizing you can find here.
这篇关于最佳尺寸调整和/或裁切逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!