I recently had to work on a project where I needed to open an image, rotate it by 90 degrees and save it again in C#. I was having some issues where it would always save the image in the PNG format regardless of what format it was loaded from. Here’s the code that I had:
1 2 3 4 5 6 7 8 |
//Load the image file Image img = Image.FromFile(filename); //Rotate the image 90 degrees to either side img.RotateFlip(RotateFlipType.Rotate90FlipNone); //Save the file back over itself img.Save(filename, img.RawFormat); //Get rid of the object img.Dispose(); |
It turns out that you can’t pass the image format into the save function directly like that. You need to save it first or it will default back to PNG format. See the following code:
1 2 3 4 5 6 7 8 9 |
//Load the image file Image img = Image.FromFile(filename); ImageFormat imgfrmt = img.RawFormat; //Rotate the image 90 degrees to either side img.RotateFlip(RotateFlipType.Rotate90FlipNone); //Save the file back over itself img.Save(filename, imgfrmt); //Get rid of the object img.Dispose(); |
I hope this helps someone.
Marc Selman says:
Thanks! I noticed the exact same thing.