我想缩放图像,但我不希望图像看起来歪斜。
图像必须为 115x115(长 x 宽)。
图片的高度(长度)不能超过 115 像素,但如果需要,宽度可以小于 115,但不能超过。
这很棘手吗?
我想缩放图像,但我不希望图像看起来歪斜。
图像必须为 115x115(长 x 宽)。
图片的高度(长度)不能超过 115 像素,但如果需要,宽度可以小于 115,但不能超过。
这很棘手吗?
您需要保留纵横比:
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 是图像的宽度/高度。
根据 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);
}
您正在寻找缩放图像并保留Aspect Ratio:
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;
查看Bertrands关于使用 GDI 和 WPF 缩放图像的博客文章。