我正在开发一个图形应用程序,我需要为每个页面保留一个缩略图。 挑战是如何在不失去性能的情况下生成缩略图文件?
目前这是我的代码:
VisualBrush VisualBrush = new VisualBrush(pageToGenerateThumbnailFor);
UIVisual.Background = VisualBrush;
RenderTargetBitmap = new RenderTargetBitmap((int)UIVisual.ActualWidth, (int)UIVisual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(UIVisual);
using (FileStream outStream = new FileStream(ThumbFileFullPath, FileMode.OpenOrCreate,
System.IO.FileAccess.ReadWrite))
{
PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
pngEncoder.Save(outStream);
}
那么,是否有更快的方法为给定的Visual生成缩略图?
由于
答案 0 :(得分:3)
我最近做了一些研究,为电子商务网站动态生成图像缩略图。我开始自己生成一个位图,然后调整大小等,类似于上面的答案。在光盘上的图像尺寸问题和质量问题后,我查看了http://imageresizing.net/,我从此没有回头看。它可以通过一行代码快速生成来自byte(),流和物理文件的图像:
ImageBuilder.Current.Build(New MemoryStream(bImage), sImageLocation + sFullFileName, New ResizeSettings("maxwidth=214&maxheight=238"))
我肯定会推荐这个组件,而不是试图重新发明轮子......
答案 1 :(得分:1)
我编写的实用程序库中的以下类对我来说效果很好,并且可以生成质量清晰的缩略图......
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
namespace Simple {
public static class ThumbnailCreator {
private static readonly object _lock = new object();
public static Bitmap createThumbnail(Stream source, Int32 width, Int32 height) {
Monitor.Enter(_lock);
Bitmap output = null;
try {
using (Bitmap workingBitmap = new Bitmap(source)) {
// Determine scale based on requested height/width (this preserves aspect ratio)
Decimal scale;
if (((Decimal)workingBitmap.Width / (Decimal)width) > ((Decimal)workingBitmap.Height / (Decimal)height)) {
scale = (Decimal)workingBitmap.Width / (Decimal)width;
}
else {
scale = (Decimal)workingBitmap.Height / (Decimal)height;
}
// Calculate new height/width
Int32 newHeight = (Int32)((Decimal)workingBitmap.Height / scale);
Int32 newWidth = (Int32)((Decimal)workingBitmap.Width / scale);
// Create blank BitMap of appropriate size
output = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
// Create Graphics surface
using (Graphics g = Graphics.FromImage(output)) {
g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
Rectangle destRectangle = new Rectangle(0, 0, newWidth, newHeight);
// Use Graphics surface to draw resized BitMap to blank BitMap
g.DrawImage(workingBitmap, destRectangle, 0, 0, workingBitmap.Width, workingBitmap.Height, GraphicsUnit.Pixel);
}
}
}
catch {
output = null;
}
finally {
Monitor.Exit(_lock);
}
return output;
}
}
}
它还保留了原始图像的宽高比。