照片拼贴:如何减少内存消耗?
问题描述:
我正在使用照片拼贴模式的WPF图像查看器。因此,在某个时间间隔内,通过在成像之后添加图像,应该在画布的随机位置上显示来自hdd上文件夹的一些图像。这些图像有一个固定的目标尺寸,它们应该缩放到,但是它们应该保持它们的纵横比。照片拼贴:如何减少内存消耗?
目前我与2个MB的图像测试我的应用程序,这增加了内存消耗相当快,让我以后在画布上约40幅得到一个OutOfMemoryException。
这是一些示例代码,我如何加载,调整大小和添加图像ATM:
void timer_Tick(object sender, EventArgs e)
{
string imagePage = foo.getNextImagePath();
BitmapImage bi = loadImage(imagePath);
int targetWidth = 200;
int targetHeight = 200;
Image img = new Image();
resizeImage(targetWidth, targetHeight, bi.PixelWidth, bi. PixelHeight, img);
img.Source = bi;
// random position
double left = RandomNumber.getRandomDouble(leftMin, leftMax);
double top = RandomNumber.getRandomDouble(topMin, topMax);
Canvas.SetLeft(image, left);
Canvas.SetTop(image, top);
imageCanvas.Children.Add(image);
}
private BitmapImage loadImage(string imagePath)
{
bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(imagePath, UriKind.Absolute);
bi.CacheOption = BitmapCacheOption.Cache;
bi.EndInit();
return bi;
}
private void resizeImage(double maxWidth, double maxHeight, double imageWidth, double imageHeight, Image img)
{
double newWidth = maxWidth;
double newHeight = maxHeight;
// calculate new size with keeping aspect ratio
if (imageWidth > imageHeight)
{// landscape format
newHeight = newWidth/imageWidth * imageHeight;
}
else
{// portrait format
newWidth = newHeight/imageHeight * imageWidth;
}
img.Width = newWidth;
img.Height = newHeight;
}
我想知道我可以减少内存使用情况。也许直接调整创建BitmapImage?任何想法,将不胜感激!提前致谢。
BTW我知道存储器消耗将通过图像的数量增加,因此,计划以限制画布图像的数量和增加另一之一,当除去最早的图像。但首先我必须弄清楚我可以在画布上显示的最佳和最大数量的图像。
答
虽然您在测试期间加载的图像大小为2MB,但我认为这是2MB文件大小,这些文件的内存中表示形式可能是此数量的许多倍。如果您正在拍摄的文件是1000x1000及调整这些到200×200,我看不出有任何需要保持较大的代表性记忆 - 所以我会说你是最有条件调整BitmapImage的对象本身,而不是渲染时(目前Image对象缩放它们,完整大小的BitmapImage对象仍然在内存中,因为它们被附加到Image.Source中)。
如果您储存的地方,你总是可以在以后的日子应该调整大小后的尺寸变化重装全尺寸图像的图像路径。
我不知道我究竟是如何能调整一个BitmapImage的与保持宽高比。如果我将DecodePixelWidth或DecodePixelHeight(仅其中之一)设置为targetSize,则应该保留长宽比,但是我需要知道在调整大小之前图像是横向还是纵向格式。创建BitmapImage,获取大小值并再次创建图像是一个很大的过载。那么我该如何处理这个问题呢? 而另一个问题:我看到您可以通过URI或通过流加载的BitmapImage并将其保存到一个字节数组。这些方法的优点是什么?何时使用哪一种? – user396363 2010-07-22 19:25:09