Search code examples
c++gdi+gdi

C++ GDIPlus Bitmap lockbits results WrongState(8)


I'm trying to get rect. of diffent area between two Bitmap* objects. When i pass 2 bitmap* it can run lockbits for first frame but it cannot do it for second bitmap.

 Rect GetRecDifference(Bitmap* currentFrame, Bitmap* previousFrame) {
if (previousFrame == NULL) {
    previousFrame = currentFrame;

}
else {
    return Rect(0, 0, 0, 0);
}

BitmapData* bd1 = new BitmapData;
Rect rect1(0, 0, currentFrame->GetWidth(), currentFrame->GetHeight());
currentFrame->LockBits(&rect1, ImageLockModeRead, PixelFormat32bppARGB, bd1);

BitmapData* bd2 = new BitmapData;
Rect rect2(0, 0, previousFrame->GetWidth(), previousFrame->GetHeight());
previousFrame->LockBits(&rect2, ImageLockModeRead, PixelFormat32bppARGB, bd2);

It can run for first one (bd1*) load status ok and last result is shows ok. but when it comes to bd2 it shows status as WrongState(8).

Is this because i copy current pointer to previous one ? What's reason can be for wrong state error ? Do i need to clear some parts from memory ?


Solution

  • The problem is that you are trying to lock the same image twice, this

    previousFrame = currentFrame;
    

    means that both your pointers are pointing to the same image.

    Instead you need a scheme that keeps two images in memory at once. Something like the following

    Bitmap* current = NULL;
    Bitmap* previous = NULL;
    while (something)
    {
        current = getNextImage(); // get the new image
        if (current && previous)
        {
            // process current and previous images
            ...
        }
        delete previous; // delete the previous image, not needed anymore
        previous = current; // save the current image as the previous
    }
    delete previous; // one image left over, delete it as well
    

    Not the only way to do it, but hopefully you get the idea.