tags:

views:

76

answers:

1

Can someone familiar with GDI shed some light on why the following sequence throws?

var b = new Bitmap("some file");
var bd= b.LockBits(rect , readonly, px); //correct size and pixel type

var clone = (Bitmap)b.Clone();
var cd = clone.LockBits(rect , readonly , px);  //okay

clone.UnlockBits(cd); //okay

b.UnlockBits(bd); //throws -- why?

It doesn't throw if I clone before locking the first bitmap, which is the behavior I expected.

I'd also expect that if it lets you clone a locked image, and then allows you to lock/unlock the clone, that the original wouldn't be affected.

+2  A: 

I think Bitmap.Clone() does not make a deep copy and the data is shared.

Edit: Following the advice given below, move the clone line just after var b and make it like this: var clone = new Bitmap(b);. It works now.

Petar Minchev
Yeah you're right Bitmap.Clone() is a object copy, I think you need to do something like: var clone = new bitmap(b);
Matt Warren
Agreed, it would try to avoid copying the pixels as long as possible.
Hans Passant
@Matt new Bitmap(b) throws when b is locked, though makes more sense in a way. You can't lock b twice though, so I don't know why it would let me get away with locking a shallow copy.
dan
also: the Scan0 of b and b.Clone() are different. weird..
dan
@dan, Well move the new Bitmap(b) before locking of the bits. I agree too with you, that cloning Bitmaps is strange.
Petar Minchev