views:

1811

answers:

4

Is there a Java library for rotating JPEG files (90/180/270 degrees) without quality degraded?

+5  A: 

I found this: http://mediachest.sourceforge.net/mediautil/

API: http://mediachest.sourceforge.net/mediautil/javadocs/mediautil/image/jpeg/LLJTran.html

Henry
very neat, great find!
Alex Beardsley
A: 

Rotation is inherently not reversible with the same fidelity due to rounding off in mapping function. Which means if you keep rotating, the quality will degrade.

Indeera
Unless you are rotating any multiple of pi/2, which means you are just changing the positions of pixels, but do not need to change their values.
Varkhan
Only if the mapping function handles these special cases separately..
Indeera
Yes, that's true. However, I think there would be a compelling argument for it to do so, since it's the most common case... for instance, putting photos taken with the camera upside down, or rotated 90° for format reasons...
Varkhan
oops, I just clarified my Q to rotating 90 / 180 / 270 degrees.
Henry
+1  A: 

In my opinion, ImageMagick is the premier piece of software to do this in. It's probably a bit of overkill for what you need, but the apis are amazing and you can pretty much do whatever you want to images with it.

Check out JMagick for the Java api.

Greg Noe
Are you sure ImageMagick does lossless JPEG rotation?
Henry
Not according to http://sylvana.net/jpegcrop/losslessapps.html .
bluej100
A: 

You don't need an external library for this kind of thing, it's all built into SE. The easiest being the rotate() function of the Graphics2D object.

For example:

   Image rotatedImage = new BufferedImage(imageToRotate.getHeight(null), imageToRotate.getWidth(null), BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = (Graphics2D) rotatedImage.getGraphics();
    g2d.rotate(Math.toRadians(90.0));
    g2d.drawImage(imageToRotate, 0, -rotatedImage.getWidth(null), null);
    g2d.dispose();

no loss!

Or, if you want to be extra careful, just use BufferedImage.getRGB(x,y), and translate it pixel by pixel on to the new image.

J_Y_C
That wouldn't be lossles, as you'd have to decode and re-encode the image, which will result in loss of data. JPEGs can be losslessly rotate in 90-degree steps, when done correctly.
Joachim Sauer
This is fine for PNG / GIF I guess, but not lossless to JPEG unfortunately.
Henry
I don't understand why you would say this isn't lossless? Especially if you are doing this operation pixel by pixel?
J_Y_C
'cause you need to first decode, then encode a JPEG.
Henry