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
}
相关文章
使用本机IIS Express开发Asp.Net Core应用图文教程
IIS Express是一个Mini版的IIS,能够支持所有的Web开发任务,本篇经验将和大家介绍使用自定义主机名来访问运行在IIS Express上的站点程序的方法,希望对大家的工作和学习有所帮助2023-06-06
在ASP.NET Core微服务架构下使用RabbitMQ实现CQRS模式的方法
ASP.NET Core微服务架构中,使用RabbitMQ作为消息队列服务,通过实现CQRS模式,将写操作和读操作分离,以提高系统的性能和可伸缩性,本文小编将为大家介绍如何在ASP.NET Core微服务架构下使用RabbitMQ来实现CQRS模式,感兴趣的朋友一起看看吧2024-01-01
datalist,Repeater和Gridview的区别分析
datalist,Repeater和Gridview的区别分析,需要的朋友可以参考一下2013-03-03


最新评论