我正在与照片拼贴模式的WPF图像查看器工作。因此,hdd上文件夹中的一些图像应该在某个时间间隔内通过在成像后添加图像来显示在画布上的随机位置上。图像有一个固定的目标大小,它们应该缩放到这个大小,但它们应该保持它们的纵横比。
目前我正在用2MB的图片测试我的应用,这会很快增加内存消耗,所以在画布上放了大约40张图片后,我就会得到一个outofmemoryexception异常。
这是一些示例代码,我如何加载,调整大小和添加图像自动柜员机:
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;
}任何想法都将不胜感激!提前谢谢。
顺便说一句,我知道内存消耗会随着图像数量的增加而增加,因此计划限制画布中的图像数量,并在添加另一个图像时删除最旧的图像。但首先,我必须弄清楚我可以在画布上显示的最好和最大图像数量是多少。
发布于 2010-07-22 09:16:08
虽然您在测试期间加载的图像大小为2MB,但我预计这是2MB的文件大小,这些文件在内存中的表示可能是这个大小的许多倍。如果你使用1000x1000的文件,并将其调整为200x200,我认为没有必要在内存中保留较大的表示形式-所以我想说,你最好调整图像对象本身的大小,而不是让BitmapImage对象在渲染时缩放它们(目前,完整大小的BitmapImage对象仍然在内存中,因为它们附加到Image.Source上)。
如果你已经将图片路径存储在某个地方,你可以随时重新加载完整大小的图片,如果调整后的大小发生变化的话。
https://stackoverflow.com/questions/3305049
复制相似问题