調整圖片大小範例
現在有很多系統都提供讓使用者加入或上傳圖片的功能,
有時候為了限制上傳圖片的尺寸,
避免使用者上傳太大的檔案,造成系統的負擔,
或是像很多照片分享網站(例如:Flickr),也會提供不同的圖片尺寸功能
如果也有類似需求,可以參考以下的範例。
.NET裡的Image這個類別,對於Image檔案的存取提供了很強大的功能,
另外再配合Graphics,就可以很容易的就去做些圖片內容的修改,
有興趣的研究看看。
參考資料:
Merging Images in .NET - The Code Project
有時候為了限制上傳圖片的尺寸,
避免使用者上傳太大的檔案,造成系統的負擔,
或是像很多照片分享網站(例如:Flickr),也會提供不同的圖片尺寸功能
如果也有類似需求,可以參考以下的範例。
.NET裡的Image這個類別,對於Image檔案的存取提供了很強大的功能,
另外再配合Graphics,就可以很容易的就去做些圖片內容的修改,
有興趣的研究看看。
public void ReSizeImage(string SourceImageFileName, string NewImageFileName)
{
double maxHeight = 600D;
double maxWidth = 800D;
Image img1 = Image.FromFile(SourceImageFileName);
double r = System.Math.Min(Convert.ToDouble(maxWidth / img1.Width), (maxHeight / img1.Height));
if (r >= 1)
throw new Exception("圖片尺寸已經小於限制尺寸");
Size s = new Size();
s.Height = Convert.ToInt32(img1.Height * r);
s.Width = Convert.ToInt32(img1.Width * r);
Image img2 = new Bitmap(img1, s);
img2.Save(NewImageFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
{
double maxHeight = 600D;
double maxWidth = 800D;
Image img1 = Image.FromFile(SourceImageFileName);
double r = System.Math.Min(Convert.ToDouble(maxWidth / img1.Width), (maxHeight / img1.Height));
if (r >= 1)
throw new Exception("圖片尺寸已經小於限制尺寸");
Size s = new Size();
s.Height = Convert.ToInt32(img1.Height * r);
s.Width = Convert.ToInt32(img1.Width * r);
Image img2 = new Bitmap(img1, s);
img2.Save(NewImageFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
}
參考資料:
Merging Images in .NET - The Code Project