Skip to content

Instantly share code, notes, and snippets.

@geekduck
Created June 20, 2014 07:51
Show Gist options
  • Save geekduck/963d57cba140922dde5e to your computer and use it in GitHub Desktop.
Save geekduck/963d57cba140922dde5e to your computer and use it in GitHub Desktop.
// Grailsの場合はBuildConfig.groovyのdependenciesに 「compile 'com.drewnoakes:metadata-extractor:2.6.2'」
@Grab(group='com.drewnoakes', module='metadata-extractor', version='2.6.2')
@Grab(group='org.imgscalr', module='imgscalr-lib', version='4.2')
import com.drew.imaging.*
import java.awt.image.*
import javax.imageio.*
import com.drew.metadata.*
import com.drew.metadata.exif.*
import org.imgscalr.*
/**
* EXIF情報のorientationに対して、正しい向きにするimgscalrの回転操作のマップ
* 例としてorientationが5の時は、imgscalrのrotateメソッドを
* Scalr.Rotation.FLIP_HORZ, Scalr.Rotation.CW_270 で呼び出すと正しい向きに戻る
*/
def exifOrientationImgscalrRotateMap = [
1: [], // そのまま
2: [ Scalr.Rotation.FLIP_HORZ ], // 上下反転
3: [ Scalr.Rotation.CW_180 ], // 180度回転
4: [ Scalr.Rotation.FLIP_VERT ], // 左右反転
5: [ Scalr.Rotation.FLIP_HORZ, Scalr.Rotation.CW_270 ], // 上下反転、270度回転
6: [ Scalr.Rotation.CW_90 ], // 90度回転
7: [ Scalr.Rotation.FLIP_HORZ, Scalr.Rotation.CW_90 ], // 上下反転、90度回転
8: [ Scalr.Rotation.CW_270 ] // 270度回転
]
/**
* Exifのorientationを取得する処理
*/
FileInputStream fis1 = new FileInputStream(new File("path/to/input/file"))
BufferedInputStream bis1 = new BufferedInputStream(fis1)
Metadata metadata = ImageMetadataReader.readMetadata(bis1, false)
int orientation = 1 // Exifデータがない場合は1(結果なにもしない)とする
// Exifデータがあるかチェックし、あるならorientationを取得する
if(metadata.containsDirectory(ExifIFD0Directory.class)){
Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION); // orientationがあるなら取得
}
fis1.close()
bis1.close()
/**
* Exifのorientationに合わせて画像の向きを正しくする処理
*/
FileInputStream fis2 = new FileInputStream(new File("path/to/input/file"))
BufferedImage sourceImg = destImg = ImageIO.read(fis2)
def rotateTask = exifOrientationImgscalrRotateMap[orientation]
// orientationに合わせてrotateメソッドを適用
rotateTask.each{ task ->
destImg = Scalr.rotate(destImg, task)
}
File newFIle = new File("path/to/output/file")
ImageIO.write(destImg, "jpg", newFIle) // ImageIOでファイル書き出すとEXIFが削除される
fis2.close()
@geekduck
Copy link
Author

Groovy(Java)でExifのOrientationを見て画像を回転するやつ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment