0

What does the following warning in Code Contracts for Net 4.0 mean and how to fix it???

CodeContracts: requires unproven: (image.PixelFormat & PixelFormat.Indexed) == 0

I'm doing either: var bmp = new Bitmap(pSize.Width, pSize.Height, System.Drawing.Imaging.PixelFormat.Indexed) or var g = Graphics.FromImage(this._otherBitmap)

As an aside: There are some questions on SO about how mature code contracts is and if you will use them and if they still exist, but they are 2009 to 2011. 2013 now... What do you think???

Thanks in advance

Community
  • 1
  • 1
Rafael Enriquez
  • 333
  • 3
  • 20
  • Please show some more context. Did you define that contract? – Daniel Hilgarth May 23 '13 at 13:13
  • Personally I think Code Contracts are fantastic. Properly implemented, they save *so* much work on boilerplate unit tests at the very least. It's still being actively developed (the last release was just a couple weeks ago), but it's true that buy-in hasn't been as strong as I would've liked. – Jeremy Todd May 23 '13 at 15:08

1 Answers1

1

The issue is that Graphics.FromImage() can't be used with an indexed bitmap, and the corresponding contract assembly (System.Drawing.Contracts.dll) contains a precondition to enforce that. The static checker can't find anything in your code to prove the requirement is satisfied, so it gives you that warning.

You'll have to make sure that this._otherBitmap is not created with the PixelFormat.Indexed format. If you're absolutely sure it's not, you could add this line above the call to Graphics.FromImage():

Contract.Assume((this._otherBitmap.PixelFormat & PixelFormat.Indexed) == 0);

...but since the warning is telling you about an actual requirement of the FromImage() method, it'll assert or throw an exception if you're wrong.

Jeremy Todd
  • 3,261
  • 1
  • 18
  • 17
  • So, @jeremy-todd what would be your recommendation??? _otherBitmap is based on bmp image, it's just that _otherBitmap is a little bit larger and has other drawing above bmp. Is there a way to ensure that PixelFormat is no Indexed??? Is Indexed a risk??? – Rafael Enriquez May 23 '13 at 16:18
  • It's not that indexed is a "risk," it's just that you can't use one to create a `Graphics` object -- it'll throw an exception if you try. You'd have to go to wherever `_otherBitmap` is created and make sure it's using a non-indexed format such as `PixelFormat.Format24bppRgb`. You might still have to add the `Contract.Assume()` line I mentioned to make the warning go away, but at least then you'd know that it's a safe assumption. – Jeremy Todd May 23 '13 at 16:23