在C#WPF中减少裁剪图像的应用程序内存

时间:2013-04-09 10:10:49

标签: c# wpf bitmapimage bitmapsource

我们通过从原始位图创建一个新的CroppedImage,在我们的WPF应用程序中显示裁剪的图像。但是当我们查看应用程序内存时,显示裁剪图像和显示原始图像是一样的。这可能不是很奇怪,因为CroppedImage保留对原始位图的引用。但是,在某种程度上可以将裁剪后的图像创建为新的位图图像,而无需引用原始位图并减少应用程序内存吗?

如何做到这一点的一些代码将受到高度赞赏。

感谢您的帮助!

[编辑] 以下是创建裁剪图像的代码:

 public class TheImage : ViewModelBase
{
    public BitmapSource CroppedImage { get; private set; }

    public TheImage(byte[] imageData)
    {
        var bitmapImage = CreateBitmapSource(imageData);
        var croppingRectangle = CalculateCropRectangle(bitmapImage.PixelWidth, bitmapImage.PixelHeight);

        CroppedImage = new CroppedBitmap(bitmapImage, croppingRectangle);

    }

    private static BitmapImage CreateBitmapSource(byte[] imageData)
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = new MemoryStream(imageData);
        bitmapImage.EndInit();
        return bitmapImage;
    }

    private static Int32Rect CalculateCropRectangle(int pixelWidth, int pixelHeight)
    {
        int width = 256;
        int height = 256;

        int x = (pixelWidth - width) / 2;
        int y = (pixelHeight - height) / 2;

        return new Int32Rect(x, y, width, height);
    }
}

1 个答案:

答案 0 :(得分:1)

你说裁剪的图像会包含对图像的引用。这使你的图像在记忆中保持不变。

你有3个选择

1:如果有处理方法

,则手动释放原始图像

2:从裁剪后的图像中删除图像的参考

3:将对旧图像的引用更改为WeakReference