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) //如果寬度超過高度以寬度為準(zhǔn)來壓縮
{
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
}
相關(guān)文章
Asp.Net Core輕量級Aop解決方案:AspectCore
這篇文章主要介紹了Asp.Net Core輕量級Aop解決方案:AspectCore,需要的朋友可以參考下2017-06-06排除JQuery通過HttpGet調(diào)用WebService返回Json時(shí)“parserror”錯(cuò)誤
排除JQuery通過HttpGet調(diào)用WebService返回Json時(shí)“parserror”錯(cuò)誤的解決方法。2011-10-10ASP.NET Core Middleware的實(shí)現(xiàn)方法詳解
中間件是組裝到應(yīng)用程序管道中以處理請求和響應(yīng)的軟件。下面這篇文章主要給大家介紹了關(guān)于ASP.NET Core Middleware實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2019-01-01Opencv2.4.13與Visual Studio2013環(huán)境搭建配置教程
這篇文章主要為大家詳細(xì)介紹了Opencv2.4.13 與Visual Studio2013環(huán)境搭建配置教程的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03ASP.NET MVC 從IHttp到頁面輸出的實(shí)例代碼
MVCHandler應(yīng)該算是MVC真正開始的地方。MVCHandler實(shí)現(xiàn)了IHttpHandler接口,ProcessRequest便是方法入口2013-09-09