如果要旋转图像,建议使用元数据提取器库http://code.google.com/p/metadata-extractor/。您可以使用以下代码获取图像信息:
public static class ImageInformation {
public final int orientation;
public final int width;
public final int height;
public ImageInformation(int orientation, int width, int height) {
this.orientation = orientation;
this.width = width;
this.height = height;
}
public String toString() {
return String.format("%dx%d,%d", this.width, this.height, this.orientation);
}
}
public static ImageInformation readImageInformation(File imageFile) throws IOException, MetadataException, ImageProcessingException {
Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
Directory directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
JpegDirectory jpegDirectory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
int orientation = 1;
try {
orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
} catch (MetadataException me) {
logger.warn("Could not get orientation");
}
int width = jpegDirectory.getImageWidth();
int height = jpegDirectory.getImageHeight();
return new ImageInformation(orientation, width, height);
}
然后根据您获取的方向,可以将图像旋转和/或翻转到正确的方向。通过以下方法给出EXIF方向的仿射变换:
public static AffineTransform getExifTransformation(ImageInformation info) {
AffineTransform t = new AffineTransform();
switch (info.orientation) {
case 1:
break;
case 2:
t.scale(-1.0, 1.0);
t.translate(-info.width, 0);
break;
case 3:
t.translate(info.width, info.height);
t.rotate(Math.PI);
break;
case 4:
t.scale(1.0, -1.0);
t.translate(0, -info.height);
break;
case 5:
t.rotate(-Math.PI / 2);
t.scale(-1.0, 1.0);
break;
case 6:
t.translate(info.height, 0);
t.rotate(Math.PI / 2);
break;
case 7:
t.scale(-1.0, 1.0);
t.translate(-info.height, 0);
t.translate(0, info.width);
t.rotate( 3 * Math.PI / 2);
break;
case 8:
t.translate(0, info.width);
t.rotate( 3 * Math.PI / 2);
break;
}
return t;
}
图像的旋转将通过以下方法完成:
public static BufferedImage transformImage(BufferedImage image, AffineTransform transform) throws Exception {
AffineTransformOp op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
BufferedImage destinationImage = op.createCompatibleDestImage(image, (image.getType() == BufferedImage.TYPE_BYTE_GRAY) ? image.getColorModel() : null );
Graphics2D g = destinationImage.createGraphics();
g.setBackground(Color.WHITE);
g.clearRect(0, 0, destinationImage.getWidth(), destinationImage.getHeight());
destinationImage = op.filter(image, destinationImage);
return destinationImage;
}
在服务器环境中,不要忘记与 -Djava.awt.headless=true
-auto-orient
命令行标志。如果要转换jpeg并希望避免重新压缩的问题,也可以使用jhead
jpeg。jhead -autorot *.jpg
应该做你需要的。恐怕我没有Java解决方案...