c# - C# 中的图像调整大小 - 确定调整大小尺寸(高度和宽度)的算法

标签 c# image-processing bitmap image-manipulation system.drawing

我需要缩小高度或宽度大于预定义像素值的图像。

我写了一些代码来查看原始图像,检查宽度、高度或者高度和宽度是否大于最大宽度/最大高度设置。

我现在需要根据后一个值的最大值找出要调整到的尺寸。

例如:如果图像是 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));
}

关于c# - C# 中的图像调整大小 - 确定调整大小尺寸(高度和宽度)的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5222711/

相关文章:

c# - 使用 PostSharp 同时验证多个项目中的类名

python - 改变 matplotlib 读取图像的方式

android - 将 View 转换为位图而不在 Android 中显示?

android 在多行文本上绘制描边

android - 在特定角落拉伸(stretch)位图

c# - 新站点的 MVC 或 Webform 架构

c# - 错误 : Incorrect syntax near '14'

c# - 将数据源绑定(bind)到 DataGridViewComboBoxColumn 时,默认值始终显示为空白

ios - 如何检测图像是灰度

php - 如何以编程方式识别成人内容?