什么是.NET中生成缩略图最快且最可靠的方法?我需要获取任何图像,将其压缩为JPEG并调整大小。
我看过几个使用GDI+和一些非免费组件的示例,我记得WPF在图像处理方面有一些好东西。尽管GDI+相当古老,但WPF可能在服务器环境下没有好处。
这必须在运行于完全信任的ASP.NET MVC应用程序中工作,并且如果可能,同步进行。
你会推荐什么?
更新:
基于Mantorok的答案,我已经制定了这个示例,但它仍然是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);
}
}
}