最好的调整大小和或裁剪逻辑
问题描述:
我碰到过这几次,并认为这将是很好的把它放在那里。什么是你最好的图像调整和/或裁剪逻辑。这个想法是,一些方法被称为目标图像,尺寸和裁剪标志 - 这将返回或保存或任何想要的图像。最好的调整大小和或裁剪逻辑
矿井在下面。从VB转换到C#所以是的,会有小错误,但逻辑是我们正在看的。
// 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
}
我怀疑这可能会更优雅,所以也许你可以做得更好。
答
我想说你应该使用标准几何类型,如Rectangle
和Size
。那么你应该也可以支持一个用例,当调用者想要将图像放在一个更大的矩形中时,但仍然想保持原始图像大小的比例。
执行调整大小的一种方法可以找到here。
感谢您的链接。 – Maleks 2009-11-01 16:55:01
有一个“谢谢”的特殊按钮:)) – 2009-11-01 23:13:44
链接被破坏 – Flexicoder 2016-01-18 16:15:59