缩放图像,但保持其比例

时间:2009-12-30 12:30:23

标签: c# asp.net image-processing image-scaling

我想缩放图像,但我不希望图像看起来偏斜。

图像必须为115x115(长x宽)。

图像的高度(长度)不能超过115像素,但如果需要,宽度可以小于115但不能超过。

这有点棘手吗?

4 个答案:

答案 0 :(得分:5)

您需要保留宽高比:

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是图像的宽度/高度。

答案 1 :(得分: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);
}

调整大小方法:

/// <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);
}

答案 2 :(得分: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;

应该对您有所帮助,如果您对这个想法感兴趣:Wikpedia article on Image Aspect Ratio

答案 3 :(得分:0)

使用GDI和WPF查看有关缩放图像的Bertrands blog post