Let's say I want a method that does some manipulation on an image by messing with its pixel values and then returns an image which is otherwise the "same" (equal PixelFormat, RawFormat, VerticalResolution, etc.).
public static Image DoSomeManipulation(this Image source)
{
    // ... 
}
I've been finding this remarkably difficult to do because to manipulate its pixels I want to use Bitmap and I can't find a way to create a Bitmap which has the same ImageFormat.
I've tried:
var target = new Bitmap(source);
and
var temp = new Bitmap(source)
var target = temp.Clone(new Rectangle(0, 0, temp.Width, temp.Height), source.PixelFormat);
and
var temp = new Bitmap(source)
var target = temp.Clone(new Rectangle(0, 0, temp.Width, temp.Height), temp.PixelFormat);
and while each of them works some of the time for my test on my 1,000 random files (PNGs, JPGs, etc.), all of them fail
Assert.AreEqual(target.ImageFormat, source.ImageFormat);
some of the time and I can't figure out why that is.
Is there any solution that doesn't involve one of
- Serializing and deserializing source(Yes, I've seen this)
- If sourceis a local file, creating copy inTempstorage or something like that
??
 
    