在.NET中生成缩略图的最快和更可靠的方法是什么?我需要获取任何图像,将其压缩为JPEG并调整其大小。
我已经看过GDI +的几个示例,一些非自由组件,并且我记得WPF在成像方面有一些不错的东西。 GDI +已经很老了,WPF在服务器环境中可能没有任何好处。
这必须在完全信任的ASP.NET MVC应用程序中工作,如果可能,还应同步运行。
你会推荐什么?
更新:
基于Mantorok's answer,我已经完成了这个示例,但是它仍然是GDI +,如果尝试使用大图像,它会崩溃:
public void GenerateThumbnail(String filename, Int32? desiredWidth,
Int32? desiredHeight, Int64 quality, Stream s)
{
using (Image image = Image.FromFile(filename))
{
Int32 width=0, height=0;
if ((!desiredHeight.HasValue && !desiredWidth.HasValue) ||
(desiredHeight.HasValue && desiredWidth.HasValue))
throw new ArgumentException(
"You have to specify a desired width OR a desired height");
if (desiredHeight.HasValue)
{
width = (desiredHeight.Value * image.Width) / image.Height;
height = desiredHeight.Value;
}
else
{
height = (desiredWidth.Value * image.Height) / image.Width;
width = desiredWidth.Value;
}
using (var newImage = new Bitmap(width, height))
using (var graphics = Graphics.FromImage(newImage))
using (EncoderParameter qualityParam =
new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
quality))
using (EncoderParameters encoderParams = new EncoderParameters(1))
{
graphics.DrawImage(image, 0, 0, width, height);
ImageCodecInfo jpegCodec = ImageCodecInfo.GetImageEncoders().
Single(e => e.MimeType.Equals("image/jpeg",
StringComparison.Ordinal));
encoderParams.Param[0] = qualityParam;
newImage.Save(s, jpegCodec, encoderParams);
}
}
}
最佳答案
对于密集的服务器端代码,我建议您使用GDI +以外的其他技术,这些技术尚未设计为逐块(以流方式)处理图像。
您可以将Windows Imaging Component 或WPF用于此任务。这里有一个很好的例子,说明如何以快速且更重要的是可扩展的方式执行此操作:
The fastest way to resize images from ASP.NET. And it’s (more) supported-ish.
关于.net - 在ASP.NET中生成图像缩略图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5882307/