我需要缩小高度或宽度大于预定义像素值的图像。
我编写了一些代码来查看原始图像,检查宽度、高度或高度和宽度是否大于最大宽度/最大高度设置。
我现在需要根据后一个值的最大值找出要调整大小的尺寸。
例如:如果图像是900h x 300w
最大高度是700h
我需要调整高度700
和宽度????
创建和保存图像文件很简单,超出了本文的范围:
// First I get the max height and width allowed:
int resizeMaxHeight = int.Parse(Utility.GetConfigValue("ResizeMaxHeight")); // in config: 700px
int resizeMaxWidth = int.Parse(Utility.GetConfigValue("ResizeMaxWidth")); // in config: 500px
// Save original:
try
{
filebase.SaveAs(savedFileName);
}
catch (System.IO.DirectoryNotFoundException ex)
{
Logger.Instance.LogException(ex, 0, "FileTransfer");
}
// Determin original dimensions:
Image image = System.Drawing.Image.FromFile(Server.MapPath(savedFileName));
int resizeHeight, resizeWidth;
bool doResize = true;
// both height and width are greater than the allowed height and width:
if (image.Width > resizeMaxWidth && image.Height > resizeMaxHeight)
{
if (image.Height > image.Width)
resizeHeight = resizeMaxHeight;
else
resizeWidth = resizeMaxWidth;
}
else if (image.Width > resizeMaxWidth)
{
// width is too great, but height is ok
resizeWidth = resizeMaxWidth;
}
else if (image.Height > resizeMaxHeight)
{
// height is too great, but width is ok
resizeHeight = resizeMaxHeight;
}
else
{
// image is ok size, don't resize:
doResize = false;
}
创建缩略图:
这就是我现在正在做的事情......不完整:
if (doResize)
{
ImageUtilities.ResizeImage(image, resizeWidth, resizeHeight);
}
如果图像高度大于图像宽度,Nathaniel 发布的解决方案实际上会失败。以下示例产生正确的结果:
private Size ResizeFit(Size originalSize, Size maxSize)
{
var widthRatio = (double)maxSize.Width / (double)originalSize.Width;
var heightRatio = (double) maxSize.Height/(double) originalSize.Height;
var minAspectRatio = Math.Min(widthRatio, heightRatio);
if (minAspectRatio > 1)
return originalSize;
return new Size((int)(originalSize.Width*minAspectRatio), (int)(originalSize.Height*minAspectRatio));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)