asp.net 图片超过指定大小后等比例压缩图片的方法
/// <summary>
/// 压缩图片
/// </summary>
/// <returns></returns>
public string resizepic()
{
#region 压缩图片开始
bool isimgfile = true; //判断是否为图片文件
string filepathname = "123"; //文件存储的路径(文件夹名称)
string filename = "a.jpg"; //上传文件的原始名称
string filesysname = datetime.now.tostring("yyyymmddhhmmssfff") + "_" + filename; //修改后的文件名称
string filepath = ""; //文件路径
string strimgpath = "/fileupload/"; //上传路径
if (isimgfile)
{
int maxwidth = 600; //图片宽度最大限制
int maxheight = 400; //图片高度最大限制
system.drawing.image imgphoto =
system.drawing.image.fromfile(server.mappath(strimgpath) + filepathname + "/" + filesysname);
int imgwidth = imgphoto.width;
int imgheight = imgphoto.height;
if (imgwidth > imgheight) //如果宽度超过高度以宽度为准来压缩
{
if (imgwidth > maxwidth) //如果图片宽度超过限制
{
float toimgwidth = maxwidth; //图片压缩后的宽度
float toimgheight = imgheight / (float)(imgwidth / toimgwidth); //图片压缩后的高度
system.drawing.bitmap img = new system.drawing.bitmap(imgphoto,
int.parse(toimgwidth.tostring()),
int.parse(toimgheight.tostring()));
string strresizepicname = server.mappath(strimgpath) + filepathname + "/_small_" + filesysname;
img.save(strresizepicname); //保存压缩后的图片
filepath = strimgpath + filepathname + "/_small_" + filesysname; //返回压缩后的图片路径
}
}
else
{
if (imgheight > maxheight)
{
float toimgheight1 = maxheight;
float toimgwidth1 = imgwidth / (float)(imgheight / toimgheight1);
system.drawing.bitmap img = new system.drawing.bitmap(imgphoto,
int.parse(toimgwidth1.tostring()),
int.parse(toimgheight1.tostring()));
string strresizepicname = server.mappath(strimgpath) + filepathname + "/_small_" + filesysname;
img.save(strresizepicname);
filepath = strimgpath + filepathname + "/_small_" + filesysname;
}
}
}
return filepath;
#endregion
}
上一篇: List集合多个复杂字段判断去重的案例