Skip to content

Instantly share code, notes, and snippets.

@mumer92
Created September 6, 2015 09:58
Show Gist options
  • Select an option

  • Save mumer92/97458e07c31cafcfd100 to your computer and use it in GitHub Desktop.

Select an option

Save mumer92/97458e07c31cafcfd100 to your computer and use it in GitHub Desktop.
Rotate iage by reading exif information
private static void rotateJpg() {
try {
File imageFile = new File(inFilePath);
BufferedImage originalImage = ImageIO.read(imageFile);
// byte[] pixels = ((DataBufferByte) originalImage.getRaster().getDataBuffer()).getData();
System.out.println(isLandscape(originalImage));
Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
ExifIFD0Directory exifIFD0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
JpegDirectory jpegDirectory = (JpegDirectory) metadata.getFirstDirectoryOfType(JpegDirectory.class);
Collection<Tag> tags = exifIFD0Directory.getTags();
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
//System.out.println(tag);
}
}
System.out.println(exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION));
int orientation = exifIFD0Directory.getInt(ExifIFD0Directory.TAG_ORIENTATION);
orientation = 6;
//6 for totated counter-clockwise by one time
// 3 for image rotated down to up : orientation = 3;
// 8 for rotated clockwise by one time
int width = jpegDirectory.getImageWidth();
int height = jpegDirectory.getImageHeight();
AffineTransform affineTransform = new AffineTransform();
switch (orientation) {
case 1:
break;
case 2: // Flip X
affineTransform.scale(-1.0, 1.0);
affineTransform.translate(-width, 0);
break;
case 3: // PI rotation
affineTransform.translate(width, height);
affineTransform.rotate(Math.PI);
break;
case 4: // Flip Y
affineTransform.scale(1.0, -1.0);
affineTransform.translate(0, -height);
break;
case 5: // - PI/2 and Flip X
affineTransform.rotate(-Math.PI / 2);
affineTransform.scale(-1.0, 1.0);
break;
case 6: // -PI/2 and -width
affineTransform.translate(height, 0);
affineTransform.rotate(Math.PI / 2);
break;
case 7: // PI/2 and Flip
affineTransform.scale(-1.0, 1.0);
affineTransform.translate(-height, 0);
affineTransform.translate(0, width);
affineTransform.rotate(3 * Math.PI / 2);
break;
case 8: // PI / 2
affineTransform.translate(0, width);
affineTransform.rotate(3 * Math.PI / 2);
break;
default:
break;
}
AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);
BufferedImage destinationImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), originalImage.getType());
destinationImage = affineTransformOp.filter(originalImage, destinationImage);
ImageIO.write(destinationImage, "jpg", new File(outFilePath));
} catch (Exception exception) {
exception.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment