[英]Resize image to lowest size with minimum quality loss
我有這段代碼來調整圖片大小:
public static void GetProductSmallThumbnail(string fileUrl, string fileName)
{
System.Drawing.Image.GetThumbnailImageAbort myCallback =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
System.Drawing.Image img = null;
FileStream fs = null;
try
{
fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);
img = System.Drawing.Image.FromStream(fs);
int orgwidth = img.Width;
int orgheight = img.Height;
int imgwidth = img.Width;
int imgheight = img.Height;
// if 240 is max width
imgwidth = 240;
imgheight = Convert.ToInt32((imgwidth * orgheight) / orgwidth);
System.Drawing.Image myThumbnail = img.GetThumbnailImage(
imgwidth, imgheight, myCallback, IntPtr.Zero);
myThumbnail.Save(Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"));
}
finally
{
fs.Close();
}
}
一切正常,但文件大小比預期的要大得多。 例如,我將此圖像用於輸入:
結果圖像具有正確的寬度和高度,但大小為 89 KB,但我希望此圖像為 7 KB
System.Drawing.Image
的Save
function 有一個重載,它接受格式作為其第二個參數(請參閱文檔)。 要以不同於原始格式的格式保存圖像,請將格式傳遞給保存函數:
myThumbnail.Save(
Path.Combine(Directory.GetCurrentDirectory(), "assets/products/small/" + fileName + ".jpg"),
ImageFormat.Jpeg);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.