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

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.

There is a program named jpegtran

jpegtran – a utility for lossless transcoding between different JPEG formats.

To rotate the image losslessly, you can do the following:

$ jpegtran -rotate 180 -perfect -outfile rotated.jpg origin.jpg

And Here is a list of applications which provide the JPEG lossless rotation feature based on the IJG code