Rotating JPEGs in .NET with minimal loss of quality
Thanks for confirming that my posted code worked. This helped me isolate my problem. I feel stupid now. My actual code had a check for image format before setting encoderParams
- but it had a bug:
if (sourceFormat == ImageFormat.Jpeg) {
// set encoderParams here
I discovered the above conditional was always false so encoderParams
wasn't being set. The fix was simple:
if (sourceFormat.Guid == ImageFormat.Jpeg.Guid) {
With any method that decompresses the image, rotates it and compresses it, you will get a loss of quality.
The JPEG format compresses color information in squares of 2x2 pixels by getting an average color to represent all four pixels, so if your image width and height are divisible by two you will lose less quality as most of the information removed in the compression is information that was interpolated in the decompression.
Likewise the brightness information is compressed in squares of 8x8 pixels, so if your width and hight are divisable by eight, the grid will align after rotating the image and you will lose less actual information.
To make a lossless rotation you have to use a completely different method, reading the JPEG file and rearranging and rotating each square of information so that it forms the rotated image without decompressing and recompressing it.