0

I have a class that wraps around a Bitmap and I would like to have a way of knowing if the bitmap has been changed (via SetPixel or GDI+).

I don't need to know exactly when it happens, I just need a way to tell if it has happened since the last check.

Now, I'm assuming that something like that isn't already packed in the Bitmap class, so what would be the best way to solve this problem?

I could provide my own wrapper functions for GetPixel and SetPixel, but then I'd have no idea if the Bitmap was changed using GDI. I COULD make a wrapper for that too but that really seems like a huge overkill.

Another possible option would be to save a copy and then check pixel by pixel. This would obviously work and would be trivial to write but it's much too slow for my needs.

Luka Horvat
  • 4,283
  • 3
  • 30
  • 48

1 Answers1

1

You should use a hash or check sum. There are some easy ways to do this but I think the simplest way would be to have a string hash property in your class then call GetHashCode() on the bitmap/binary string/whatever container you're storing it in. Set it to the classes property, check the current hashcode against that value to see if anything has changed. You could also write your own little checksum function or choose from (I'm sure) a vast array of third party options.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • This seems great but isn't the hash calculated by iterating through all the pixels anyways? How is it faster than iterating through them and check one by one? – Luka Horvat Nov 25 '13 at 22:30
  • @LukaHorvat it may not be any faster. Of course it's simpler to call that method than write you own though and I imagine that method is highly optimized. The only real way to tell if the file has changed is by looking at the binary, the hash/check sum is just a faster simpler way of doing this. – evanmcdonnal Nov 25 '13 at 22:32
  • Here's another checksum/hashing option; http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file also worth pointing out these methods don't require you to save multiple copies of the file so it's definitely has some minor advantages there. In either case your performance isn't going to get any better than this. The hash/checksum is a unique value to represent the file. You can't avoid doing a bit by bit comparison. – evanmcdonnal Nov 25 '13 at 22:34
  • I guess that the only way to have a faster alternative would be if the bitmap tracked the changes when they happen. Though, I'm pretty sure GDI changes it's binary data directly, so there's no real way to know if you don't check pixel by pixel. Alright. Thank you. – Luka Horvat Nov 25 '13 at 22:37
  • @LukaHorvat if you're talking about the file literally changing on disk then you can just check the last write time. – evanmcdonnal Nov 25 '13 at 22:38
  • No. Unfortunately, I'm talking about an instance of the Bitmap class in System.Drawing. – Luka Horvat Nov 25 '13 at 22:46