Bitmap.Clone() doesn't always honor requested PixelFormat and thus results in Stackoverflow in Encode() recursion.
- Dominant language
- C#
- Stars
- 144
- Forks
- 46
- PR merge metrics
- No merged PRs in 30d
Description
Hi there!
Fyi, the following method generates a stackoverflow exception here due to recursion with certain PixcelFormats:
Inside SimpleEncoder.cs...
public void Encode(Bitmap b, float quality, out IntPtr result, out long length)
{
if (b.PixelFormat == PixelFormat.Format32bppArgb)
{
...convert...
}
else if (b.PixelFormat == PixelFormat.Format24bppRgb)
{
...convert...
}
else
{
// The problem occurs here with some input PixelFormat types.
// Notably PixelFormat = 8207 (undocumented non-enum value) occurs from streaming in a CMYK jpg
// https://stackoverflow.com/questions/5065371
// The bitmap.Clone() result below does not honor the requested the pixel format and
// returning the same PixelFormat type and so the recursive call ends up in this
// same block until a stackoverflow exception.
// From this other related issue, there are other types then PixelFormat 8207 where
// this happens: https://stackoverflow.com/questions/2016406
//
// To resolve, suggest using an GDI approach like the first answer here which
// uses Graphics to write into a new bitmap() for all pixelformats instead of Clone().
// https://stackoverflow.com/a/2016509/538763
// I have verified the answer to work against 8207 (outside of the library code).
using Bitmap b2 = b.Clone(new Rectangle(0, 0, b.Width, b.Height), PixelFormat.Format32bppArgb);
Encode(b2, quality, out result, out length); // RECURSE
}
And thanks for the library!
Contributor guide
No contributing guide indexed for this repository
Research direction
Start in SimpleEncoder.cs at Encode(Bitmap b, float quality, out IntPtr result, out long length), especially the fallback handling of unsupported PixelFormat values. Reproduce the CMYK JPEG case with PixelFormat 8207 and verify that conversion produces a supported format, avoids recursive Encode calls, and completes encoding without a StackOverflowException.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- computer-graphics
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 48/100