我正在使用照片拼貼模式的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我知道存儲器消耗將通過圖像的數量增加,因此,計劃以限制畫布圖像的數量和增加另一之一,當除去最早的圖像。但首先我必須弄清楚我可以在畫布上顯示的最佳和最大數量的圖像。
我不知道我究竟是如何能調整一個BitmapImage的與保持寬高比。如果我將DecodePixelWidth或DecodePixelHeight(僅其中之一)設置爲targetSize,則應該保留長寬比,但是我需要知道在調整大小之前圖像是橫向還是縱向格式。創建BitmapImage,獲取大小值並再次創建圖像是一個很大的過載。那麼我該如何處理這個問題呢? 而另一個問題:我看到您可以通過URI或通過流加載的BitmapImage並將其保存到一個字節數組。這些方法的優點是什麼?何時使用哪一種? – user396363 2010-07-22 19:25:09