[英]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.