使用纵横比和裁剪中心图像调整C#中的图像大小,以便没有间隙
我正在尝试将用户上传的图像调整为横向尺寸,例如450w和250h,同时保持纵横比,但为了避免调整大小的图像(如侧面有间隙的肖像图像),我希望裁剪图像的中心以填充调整大小的尺寸使用纵横比和裁剪中心图像调整C#中的图像大小,以便没有间隙,c#,asp.net,C#,Asp.net,我正在尝试将用户上传的图像调整为横向尺寸,例如450w和250h,同时保持纵横比,但为了避免调整大小的图像(如侧面有间隙的肖像图像),我希望裁剪图像的中心以填充调整大小的尺寸 我已经找到了很多代码,可以在保持纵横比的同时调整图像大小,但这不是我上面要找的,我希望有人能帮助我。你应该通过needToFill=true: public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool need
我已经找到了很多代码,可以在保持纵横比的同时调整图像大小,但这不是我上面要找的,我希望有人能帮助我。你应该通过needToFill=true:
public static System.Drawing.Image FixedSize(Image image, int Width, int Height, bool needToFill)
{
#region calculations
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;
}
}
图像大小存在问题,裁剪后的图像大小约为原始图像的两倍。修复了吗?我遇到了同样的问题,新裁剪图像的文件大小与原始图像大致相同。有两个选项对我有效:将PixelFormat更改为较便宜的每像素32位,将水平和垂直分辨率设置为72(如果用于web),最后在保存时确保您指定的图像格式与ImageFormat.jpeg一样对我有效,但唯一的问题是图像会缩放,所以不会显示整个图像。有什么建议吗?如果图像的宽度或高度小于所需的宽度和高度,则不起作用。有什么建议吗?我通过注释这些行找到了答案-如果(nScale>1)nScale=1;