1

我有以下两个课程:

public class ImageHandler
{
    private Bitmap _currentBitmap;
    private Bitmap _bitmapbeforeProcessing;

    public Bitmap CurrentBitmap
    {
        get
        {
            if (_currentBitmap == null)
            {
                _currentBitmap = new Bitmap(1, 1);
            }
            return _currentBitmap;
        }
        set { _currentBitmap = value; }
    }

    public string CurrentBitmapPath { get; set; }

    public void ResetBitmap()
    {
        if (_currentBitmap != null && _bitmapbeforeProcessing != null)
        {
             Bitmap temp = (Bitmap)_currentBitmap.Clone();
            _currentBitmap = (Bitmap)_bitmapbeforeProcessing.Clone();
            _bitmapbeforeProcessing = (Bitmap)temp.Clone();
        }
    }

    internal void RestorePrevious()
    {
        _bitmapbeforeProcessing = _currentBitmap;
    }
 }

和:

public class RotationHandler
{
    private ImageHandler imageHandler;

    public void Flip(RotateFlipType rotateFlipType)
    {
        this.imageHandler.RestorePrevious();
        Bitmap bitmap = (Bitmap) this.imageHandler.CurrentBitmap.Clone();
        this.imageHandler.CurrentBitmap.Dispose(); // dispose of current bitmap
        bitmap.RotateFlip(rotateFlipType);
        this.imageHandler.CurrentBitmap = bitmap;
   }
 }

ResetBitmap()旋转后调用时,显示:

参数无效

但如果:

this.imageHandler.CurrentBitmap.Dispose();

被评论然后它工作正常。但是,如果Flip()多次调用方法,则会发生 Out Of Memory 异常。

我该如何解决?

4

2 回答 2

1

虽然 Bitmap 是一个 C# 对象,但它实际上是一个 win32 对象,因此,您必须在完成后调用 Dispose()。

你正在做:

_CurrentBitmap = _CurrentBitmap.Clone();

当你应该做的时候:

_Temp = _CurrentBitmap.Clone();
_CurrentBitmap.Dispose();
_CurrentBitmap = _Temp;
于 2012-04-16T16:13:11.807 回答
0

我刚刚处理了具有相同错误的类似问题。

调用Clone()一个Bitmap对象只会创建一个浅拷贝;它仍将引用相同的底层图像数据,因此调用Dispose()其中一个对象将删除原始和副本的数据。调用RotateFlip()已处置的Bitmap对象会导致您看到的异常:

System.ArgumentException:参数无效

解决此问题的一种方法是Bitmap基于原始对象创建一个新对象,而不是使用Clone(). 这将复制图像数据以及托管对象数据。

例如,而不是:

Bitmap bitmap = (Bitmap) this.imageHandler.CurrentBitmap.Clone();

利用:

Bitmap bitmap = new Bitmap(this.imageHandler.CurrentBitmap);

请注意,如果源位图对象为空,这也会导致ArgumentException,因此通常以下更好(为简洁起见,我将源位图重命名currentBitmap为):

Bitmap bitmap = (currentBitmap == null) ? null : new Bitmap(currentBitmap)
于 2019-02-26T13:10:54.183 回答