调整图片大小,但保持其比例

8
我想缩放图片,但不希望图片看起来扭曲。
图片的尺寸必须是115x115(长度x宽度)。
图片的高度不能超过115像素(长度),但如果需要,宽度可以小于115像素但不能更大。
这很棘手吗?

这似乎与https://dev59.com/03E85IYBdhLWcg3wViA4相似。请查看我对那个问题的回答。 - Kevin Kibler
4个回答

6

您需要保持宽高比:

float scale = 0.0;

    if (newWidth > maxWidth || newHeight > maxHeight)
    {
        if (maxWidth/newWidth < maxHeight/newHeight)
        {
            scale = maxWidth/newWidth;
        }
        else
        {
            scale = maxHeight/newHeight;
        }
        newWidth = newWidth*scale;
        newHeight = newHeight*scale;

    }

在代码中,newWidth/newHeight 最初是图像的宽度/高度。

如果newHeight或newWidth是整数,它将无法正常工作,您需要将其转换为float - BrunoLM

4

根据Brij的回答,我制作了这个扩展方法:

/// <summary>
/// Resize image to max dimensions
/// </summary>
/// <param name="img">Current Image</param>
/// <param name="maxWidth">Max width</param>
/// <param name="maxHeight">Max height</param>
/// <returns>Scaled image</returns>
public static Image Scale(this Image img, int maxWidth, int maxHeight)
{
    double scale = 1;

    if (img.Width > maxWidth || img.Height > maxHeight)
    {
        double scaleW, scaleH;

        scaleW = maxWidth / (double)img.Width;
        scaleH = maxHeight / (double)img.Height;

        scale = scaleW < scaleH ? scaleW : scaleH;
    }

    return img.Resize((int)(img.Width * scale), (int)(img.Height * scale));
}

/// <summary>
/// Resize image to max dimensions
/// </summary>
/// <param name="img">Current Image</param>
/// <param name="maxDimensions">Max image size</param>
/// <returns>Scaled image</returns>
public static Image Scale(this Image img, Size maxDimensions)
{
    return img.Scale(maxDimensions.Width, maxDimensions.Height);
}

resize方法:

/// <summary>
/// Resize the image to the given Size
/// </summary>
/// <param name="img">Current Image</param>
/// <param name="width">Width size</param>
/// <param name="height">Height size</param>
/// <returns>Resized Image</returns>
public static Image Resize(this Image img, int width, int height)
{
    return img.GetThumbnailImage(width, height, null, IntPtr.Zero);
}

我在编程中遇到了这样一个问题:使用VS 2010 .net 4时,img.Source.Height比img.Height更适用。此外,Width也需要使用Source属性。 - mnemonic

2

您希望缩放图像并保留长宽比

float MaxRatio = MaxWidth / (float) MaxHeight;
float ImgRatio = source.Width / (float) source.Height;

if (source.Width > MaxWidth)
return new Bitmap(source, new Size(MaxWidth, (int) Math.Round(MaxWidth /
ImgRatio, 0)));

if (source.Height > MaxHeight)
return new Bitmap(source, new Size((int) Math.Round(MaxWidth * ImgRatio,
0), MaxHeight));

return source;

我能帮助你,如果你对这个想法感兴趣的话,可以查看维基百科关于图像长宽比的文章


刚试过这段代码(在搜索同样基本问题时在其他地方找到),如果您从宽度和高度都大于最大值的图像开始,则实际上无法完成工作-您需要根据原始图像的哪个维度最大来应用第一或第二缩放,否则您最终会得到一个维度比任何缩放中允许的最大值更大。 - user32826

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接