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
}
相關(guān)文章
使用本機IIS?Express開發(fā)Asp.Net?Core應(yīng)用圖文教程
IIS Express是一個Mini版的IIS,能夠支持所有的Web開發(fā)任務(wù),本篇經(jīng)驗將和大家介紹使用自定義主機名來訪問運行在IIS?Express上的站點程序的方法,希望對大家的工作和學習有所幫助2023-06-06
ASP.NET 實現(xiàn)驗證碼以及刷新驗證碼的小例子
這篇文章介紹了ASP.NET 實現(xiàn)驗證碼以及刷新驗證碼的小例子,有需要的朋友可以參考一下2013-10-10
在ASP.NET2.0中通過Gmail發(fā)送郵件的代碼
我們有時候需要發(fā)送郵件給訪問網(wǎng)頁的用戶,例如,注冊的時候,發(fā)一確認信什么的。那么,在ASP.NET2.0中該如果操作呢?2008-06-06
在ASP.NET?Core微服務(wù)架構(gòu)下使用RabbitMQ實現(xiàn)CQRS模式的方法
ASP.NET Core微服務(wù)架構(gòu)中,使用RabbitMQ作為消息隊列服務(wù),通過實現(xiàn)CQRS模式,將寫操作和讀操作分離,以提高系統(tǒng)的性能和可伸縮性,本文小編將為大家介紹如何在ASP.NET Core微服務(wù)架構(gòu)下使用RabbitMQ來實現(xiàn)CQRS模式,感興趣的朋友一起看看吧2024-01-01
datalist,Repeater和Gridview的區(qū)別分析
datalist,Repeater和Gridview的區(qū)別分析,需要的朋友可以參考一下2013-03-03

