我有一个 C# 函数来调整图像大小。函数的参数是原始图像路径、新图像路径(保存图像大小调整后的路径)。现在我想为以下要求建立一个逻辑。
1. 如果原始文件的宽度大于 480 或小于 450 ,那么我想将输出图像的宽度设置为 450px。并且高度必须与宽度成比例。
- 如果原始文件的宽度 > 其高度,则在顶部和底部(高度)添加空白区域,以便新高度为 650。
我正在使用以下代码来调整图像大小
try
{
Size oldSize=new Size();
Bitmap oldbmp1 = (Bitmap) Bitmap.FromFile(originalpath);
oldSize.Width=oldbmp1.Width;
oldSize.Height=oldbmp1.Height;
Size newSize=new Size()
using (Bitmap newbmp = new Bitmap(newsize.Width, newsize.Height), oldbmp = Bitmap.FromFile(originalpath) as Bitmap)
{
Graphics newgraphics = Graphics.FromImage(newbmp);
newgraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
// newsize = GetNewImageSize(oldSize); // here i want the new Size
newgraphics.Clear(Color.FromArgb(-1));
newgraphics.FillRectangle(Brushes.White, 0, 0, newsize.Width, newsize.Height);
newgraphics.DrawImage(oldbmp, 0, 0, newsize.Width, newsize.Height);
try
{
// newgraphics.Save();
ImageCodecInfo[] Info = ImageCodecInfo.GetImageEncoders();
EncoderParameters Params = new EncoderParameters(1);
Params.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
newbmp.Save(newpath, Info[1], Params);
}
catch (Exception ex1)
{
throw ex1;
}
finally
{
newbmp.Dispose();
oldbmp.Dispose();
oldbmp1.Dispose();
}
}
}
catch (Exception ee)
{
throw ee;
}
任何人都可以建议我对此还有什么要补充的吗?
编辑(因为评论字段不允许我有更多的字符)
我试过这个
float ratio = oldImg.Width / oldImg.Height;
SizeF newSize = new SizeF(desiredWidth, desiredWidth * ratio);
但它不会像我希望的那样工作 例如:我的原始图像宽度为 450,高度为 1094。所以比率 = 450/1094,即 0.4113;所需高度=所需宽度*比率即;450*0.4113 即 185 .1
其比例如何。我认为有些事情必须纠正。还有什么想法吗?
提前致谢