C#中如何调整图像大小

发表于:2016-10-18 10:31

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:麦穗技术    来源:51Testing软件测试网采编

  在本篇文章中,我将介绍如何在C#中来调整你想要的图像大小。要实现这一目标,我们可以采取以下几个步骤:
  1.首先要获取你想要调整大小的图像:
  string path = Server.MapPath("~/Images");
  System.Drawing.Image img = System.Drawing.Image.FromFile(string.Concat(path,"/3904.jpg"));
  2.将图像转换为Bitmap:
  Bitmap b = new Bitmap(img);
  3.创建一个调整图像大小的方法:
private static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
//获取图片宽度
int sourceWidth = imgToResize.Width;
//获取图片高度
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//计算宽度的缩放比例
nPercentW = ((float)size.Width / (float)sourceWidth);
//计算高度的缩放比例
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//期望的宽度
int destWidth = (int)(sourceWidth * nPercent);
//期望的高度
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (System.Drawing.Image)b;
}
  在上面的方法中,我们获取了位图图像,然后绘制了不同尺寸的图像(这里绘制出的图像是基于指定的纵横比)
  4.调用上述方法,得到调整大小之后
  System.Drawing. Image i = resizeImage(b, new Size(100, 100));
  输出结果:
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号