调整图像在C#中纵横比和作物中心图像所以不存在任何差距 [英] Resize image in C# with aspect ratio and crop central image so there are no gaps
本文介绍了调整图像在C#中纵横比和作物中心图像所以不存在任何差距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图调整用户上传的图片的一道风景尺寸如450瓦特和250H,同时保持纵横比,但要避免就像在旁边空白的纵向图像缩放后的图像,我想裁剪图像的中心,填补了调整大小的尺寸。
I'm trying to resize user uploaded images to a landscape dimensions e.g. 450w and 250h while maintaining aspect ratio, but to avoid resized images like portrait images having gaps on the side I would like to crop the centre of the image to fill the resized dimensions.
我发现很多code的来调整图像,同时保持纵横比,但不是我上面找,我希望有人可以提供帮助。
I have found plenty of code to resize images while maintaining aspect ratio but not what I am looking for above, I'm hoping someone can help.
推荐答案
您应该通过needToFill =真:
You should pass needToFill = true:
public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool needToFill)
{
#region много арифметики
int sourceWidth = image.Width;
int sourceHeight = image.Height;
int sourceX = 0;
int sourceY = 0;
double destX = 0;
double destY = 0;
double nScale = 0;
double nScaleW = 0;
double nScaleH = 0;
nScaleW = ((double)Width / (double)sourceWidth);
nScaleH = ((double)Height / (double)sourceHeight);
if (!needToFill)
{
nScale = Math.Min(nScaleH, nScaleW);
}
else
{
nScale = Math.Max(nScaleH, nScaleW);
destY = (Height - sourceHeight * nScale) / 2;
destX = (Width - sourceWidth * nScale) / 2;
}
if (nScale > 1)
nScale = 1;
int destWidth = (int)Math.Round(sourceWidth * nScale);
int destHeight = (int)Math.Round(sourceHeight * nScale);
#endregion
System.Drawing.Bitmap bmPhoto = null;
try
{
bmPhoto = new System.Drawing.Bitmap(destWidth + (int)Math.Round(2 * destX), destHeight + (int)Math.Round(2 * destY));
}
catch (Exception ex)
{
throw new ApplicationException(string.Format("destWidth:{0}, destX:{1}, destHeight:{2}, desxtY:{3}, Width:{4}, Height:{5}",
destWidth, destX, destHeight, destY, Width, Height), ex);
}
using (System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto))
{
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.SmoothingMode = SmoothingMode.HighQuality;
Rectangle to = new System.Drawing.Rectangle((int)Math.Round(destX), (int)Math.Round(destY), destWidth, destHeight);
Rectangle from = new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight);
//Console.WriteLine("From: " + from.ToString());
//Console.WriteLine("To: " + to.ToString());
grPhoto.DrawImage(image, to, from, System.Drawing.GraphicsUnit.Pixel);
return bmPhoto;
}
}
这篇关于调整图像在C#中纵横比和作物中心图像所以不存在任何差距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文