我的应用程序一次显示大量图像缩略图。目前,我将所有全尺寸图像保留在内存中,并简单地在 UI 中缩放图像以创建缩略图。但是,我宁愿只在内存中保留小缩略图,并且仅在必要时加载全尺寸图像。
我认为这很容易,但与仅在 UI 中缩放全尺寸图像相比,我生成的缩略图非常模糊。
图像是没有标题信息的字节数组。我提前知道大小和格式,因此我可以使用 BitmapSource.Create 来创建 ImageSource。
//This image source, when bound to the UI and scaled down creates a nice looking thumbnail
var imageSource = BitmapSource.Create(
imageWidth,
imageHeight,
dpiXDirection,
dpiYDirection,
format,
palette,
byteArray,
stride);
using (var ms = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageSource);
encoder.Save(ms);
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
//I can't just create a MemoryStream from the original byte array because there is no header info and it doesn't know how to decode the image!
bi.StreamSource = ms;
bi.DecodePixelWidth = 60;
bi.EndInit();
//This thumbnail is blurry!!!
Thumbnail = bi;
}
我猜它很模糊,因为我首先将其转换为 png,但是当我使用 BmpBitmapEncoder 时,我收到“没有可用的成像组件”错误。在本例中,我的图像是 Gray8,但我不确定为什么 PngEncoder 可以计算出来,但 BmpEncoder 不能。
当然,必须有某种方法可以从原始 ImageSource 创建缩略图,而不必先将其编码为位图格式?我希望 BitmapSource.Create 只是让您像 BitmapImage 类一样指定解码宽度/高度。
EDIT
最终答案是使用 TransformBitmap 和 WriteableBitmap 来创建缩略图并消除原始的全尺寸图像。
var imageSource = BitmapSource.Create(...raw bytes and stuff...);
var width = 100d;
var scale = width / imageSource.PixelWidth;
WriteableBitmap writable = new WriteableBitmap(new TransformedBitmap(imageSource, new ScaleTransform(scale, scale)));
writable.Freeze();
Thumbnail = writable;