今天在幫青牧弄相簿功能時, 每張相片都需要一張至兩張的縮圖 , 所以我寫了一個簡單的小方法, 按照width的數值 , 照比例的縮小.
程式碼如下
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
private bool setNewImag(string oldFileName,int width)
{
string imgPath = "~/UploadFiles/photo/";
string fileName = oldFileName;
Image imgSource = Image.FromFile(Server.MapPath(imgPath + fileName));
int sourceWidth = imgSource.Width;
int sourceHeight = imgSource.Height;
int 比例 = (int)(imgSource.Width / width);
string newImgName = Path.GetFileNameWithoutExtension(fileName) +
"_new1" + Path.GetExtension(fileName);
Image newImg0 =
imgSource.GetThumbnailImage((int)(sourceWidth / 比例),
(int)(sourceHeight / 比例),
null, (IntPtr)0);
Image newImg =
imgSource.GetThumbnailImage((int)(sourceWidth / 比例),
(int)(sourceHeight / 比例),
null, (IntPtr)0);
newImg.Save(Server.MapPath(imgPath + newImgName));
return File.Exists(Server.MapPath(imgPath + newImgName));
}
可能你會好奇, 中間我怎麼縮圖兩次,而取第二次呢?
Image newImg0 =
imgSource.GetThumbnailImage((int)(sourceWidth / 比例),
(int)(sourceHeight / 比例),
null, (IntPtr)0);
Image newImg =
imgSource.GetThumbnailImage((int)(sourceWidth / 比例),
(int)(sourceHeight / 比例),
null, (IntPtr)0);
網路上有人測試過, 用imgSource.GetThumbnailImage(),同一張圖縮兩次,第二次效果比較好?
有興趣的人可以自已玩玩看喔.
Recommend to Front page
未分類(1)
Comment Permissions: Allow commenting