我需要縮小高度或寬度大於預定義像素值的圖像。C#中的圖像調整大小 - 確定調整大小尺寸(高度和寬度)的算法
我寫了一些代碼,看看原始圖像,檢查寬度,高度或高度和寬度是否大於最大寬度/最大高度設置。
我現在需要根據後者的最大值找出調整大小的尺寸。
例如:如果圖像是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);
}
是是的是!計算長寬比。這是我正在尋找的術語。太棒了,非常感謝。 – nocarrier 2011-03-07 17:23:07
不客氣。我建議你也讀這篇文章 - 有很多陷阱在.NET圖像調整大小,你應該避開: http://nathanaeljones.com/163/20-image-resizing-pitfalls/ – 2011-03-07 20:15:25
這個答案實際上失敗,如果圖像比它寬廣! – 2017-12-05 09:00:05