웹개발자/java
이미지 업로드 가로 세로 회전 현상 처리
wlsufld
2020. 3. 1. 23:21
1. dependency 추가.
<!-- image EXIF read -->
<dependency>
<groupId>com.drewnoakes</groupId>
<artifactId>metadata-extractor</artifactId>
<version>2.9.1</version>
</dependency>
</dependencies>
2. java 코드 수정
private void makeThumbnail(String filePath, String fileName, String fileExt) throws Exception {
int maxWidth = 250, maxHeight = 250; // 썸네일 가로 세로 사이즈
//파일을 읽는다.
File imageFile = new File(filePath);
// 원본 파일의 Orientation 정보를 읽는다.
int orientation = 1; // 회전정보, 1. 0도, 3. 180도, 6. 270도, 8. 90도 회전한 정보
int width = 0; // 이미지의 가로폭
int height = 0; // 이미지의 세로높이
Metadata metadata; // 이미지 메타 데이터 객체
Directory directory; // 이미지의 Exif 데이터를 읽기 위한 객체
JpegDirectory jpegDirectory; // JPG 이미지 정보를 읽기 위한 객체
try {
metadata = ImageMetadataReader.readMetadata(imageFile);
directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
jpegDirectory = metadata.getFirstDirectoryOfType(JpegDirectory.class);
if(directory != null){
orientation = directory.getInt(ExifIFD0Directory.TAG_ORIENTATION); // 회전정보
}
}catch (Exception e) {
orientation=1;
}
//imageFile
BufferedImage srcImg = ImageIO.read(imageFile);
// 회전 시킨다.
switch (orientation) {
case 6:
srcImg = Scalr.rotate(srcImg, Scalr.Rotation.CW_90, null);
break;
case 1:
break;
case 3:
srcImg = Scalr.rotate(srcImg, Scalr.Rotation.CW_180, null);
break;
case 8:
srcImg = Scalr.rotate(srcImg, Scalr.Rotation.CW_270, null);
break;
default:
orientation=1;
break;
}
BufferedImage destImg = Scalr.resize(srcImg, maxWidth, maxHeight);
// 썸네일을 생성하여 저장, 파일명 뒤에 _THUMB 추가
String thumbName = filePath + "_THUMB" ;
File thumbFile = new File(thumbName);
ImageIO.write(destImg, fileExt.toUpperCase(), thumbFile);
}
참고 : stackoverflow
끝.