Search code examples
graphicscompressionjpeglossy-compression

Can a JPEG compressed image be rotated without a loss in quality?


JPEG is a lossy compression scheme, so decompression-manipulation-recompression normally reduces the image quality further for each step. Is it possible to rotate a JPEG image without incurring further loss? From what little I know of the JPEG algorithm, it naively seems possible to avoid further loss with a bit of effort. Which common image manipulation programs (e.g. GIMP, Paint Shop Pro, Windows Photo Gallery) and graphic libraries cause quality loss when performing a rotation and which don't?


Solution

  • Yes, it is possible for certain cases: 90-degree rotations and flips on images. The heart of the JPEG algorithm -- the lossy part -- involves breaking the image into 8x8 pixel blocks, performing a discrete cosine transform on the block and then quantizing the result. There's also some color space conversion and lossless compression of the blocks on top of this.

    Rotating or flipping an 8x8 block will give a DCT with the same basic coefficients, but possibly transposed and/or with some sign changes depending on the transformation. So the basic steps to rotate or flip an image losslessly would involve:

    1. Decompress and extract the blocks
    2. Transpose and/or sign flip the DCT coefficients for each block
    3. Reshuffle the blocks into their new order (otherwise the 8x8 blocks would be rotated but still in the old place)
    4. Recompress it all with the lossless compression steps.