我尝试将用户用户上传的图片缩放并裁剪为基于3条规则的250px x 250px头像图片:
如果上传的图片为方形,则调整为250px x 250px
如果上传的图片是横向,请将比例高度调整为250px和宽度,并水平居中裁剪窗口。
如果上传的图片是纵向,请按比例缩放宽度为250像素和高度,垂直居中裁剪窗口。
调整大小似乎有效,但保存的图像似乎没有被裁剪到正方形?
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
//Square
if (image.Width == image.Height)
{
var newImage = new Bitmap(maxWidth, maxHeight);
return newImage;
}
//Landscape
else if (image.Width > image.Height)
{
var ratioY = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratioY);
var newHeight = maxHeight;
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.DrawImage(image, ((newWidth - maxWidth) / 2), 0, maxWidth, maxHeight);
}
return newImage;
}
//Portrait
else
{
var ratioX = (double)maxWidth / image.Width;
var newHeight = (int)(image.Height * ratioX);
var newWidth = maxWidth;
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.DrawImage(image, 0, ((newHeight - maxHeight) / 2), newWidth, newHeight);
}
return newImage;
}
}
答案 0 :(得分:0)
我没有使用过绘图API,但是当它们已经是正方形时,你似乎没有调整图像大小。
尝试使用方块:
//Square
if (image.Width == image.Height)
{
var newImage = new Bitmap(maxWidth, maxHeight);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}