我的位图具有如下长宽比,或者可能是任何长宽比。
当用户指定一个选项时,我需要一种从这些图像中裁剪出周围部分的方法,以便生成纵横比为1:1的图像。像这样
我想我将以这些图像的中心点并裁剪出侧面。
我已经在Web平台中找到了此方法。.但是位图没有Crop
方法
public static WebImage BestUsabilityCrop(WebImage image, decimal targetRatio)
{
decimal currentImageRatio = image.Width / (decimal)image.Height;
int difference;
//image is wider than targeted
if (currentImageRatio > targetRatio)
{
int targetWidth = Convert.ToInt32(Math.Floor(targetRatio * image.Height));
difference = image.Width - targetWidth;
int left = Convert.ToInt32(Math.Floor(difference / (decimal)2));
int right = Convert.ToInt32(Math.Ceiling(difference / (decimal)2));
image.Crop(0, left, 0, right);
}
//image is higher than targeted
else if (currentImageRatio < targetRatio)
{
int targetHeight = Convert.ToInt32(Math.Floor(image.Width / targetRatio));
difference = image.Height - targetHeight;
int top = Convert.ToInt32(Math.Floor(difference / (decimal)2));
int bottom = Convert.ToInt32(Math.Ceiling(difference / (decimal)2));
image.Crop(top, 0, bottom, 0);
}
return image;
}
请提出解决此问题的方法。
您可以使用如下所示的内容:
public static Image Crop(Image source)
{
if (source.Width == source.Height) return source;
int size = Math.Min(source.Width, source.Height);
var sourceRect = new Rectangle((source.Width - size) / 2, (source.Height - size) / 2, size, size);
var cropped = new Bitmap(size, size);
using (var g = Graphics.FromImage(cropped))
g.DrawImage(source, 0, 0, sourceRect, GraphicsUnit.Pixel);
return cropped;
}
这确实是从中心开始裁剪的。如果您想从底部/右侧进行裁剪,请使用var sourceRect = new Rectangle(0, 0, size, size);
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句