我想缩放图片,但不希望图片看起来扭曲。
图片的尺寸必须是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;
}
float
。 - BrunoLM根据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);
}
您希望缩放图像并保留长宽比:
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;
我能帮助你,如果你对这个想法感兴趣的话,可以查看维基百科关于图像长宽比的文章