티스토리 뷰

반응형

 JAVA에서 이미지의 메타데이터에 접근할 수있는 표준 라이브러리는 현재 없다.(JAVA8 기준) 하지만 외부 라이브러리를 통해 편리하게 메타데이터를 가져올 수 있다. 아래 링크를 참고하자.


 https://drewnoakes.com/code/exif/


 링크를 참조하면, directory와 tag라는 것을 통해 이미지의 메타데이터에 접근할 수 있음을 확인할 수 있다. 다만 주의해야할 것이 있는데, Exif는 JPEG파일에서만 제공된다는 점이다.




 아래 예제는 File Class 형태의 이미지파일에 대한 모든 메타데이터를 출력하는 예제이다. 




Metadata metadata = ImageMetadataReader.readMetadata(file);
 
for (Directory directory : metadata.getDirectories()) {
    for (Tag tag : directory.getTags()) {
        System.out.format("[%s] - %s = %s",
            directory.getName(), tag.getTagName(), tag.getDescription());
    }
    if (directory.hasErrors()) {
        for (String error : directory.getErrors()) {
            System.err.format("ERROR: %s", error);
        }
    }
}




 그런데 메타데이터는 정말 많은 항목들이 있으므로, 필요한 것만 가져오는 것이 편할 것이다. 비슷한 값도 많고, 전부 다 정리하기엔 너무 많기도하다. 필요한 항목만 가져오는 것은 아래와 같이 구현한다.


Metadata metadata = ImageMetadataReader.readMetadata(file);
 
// 디렉토리 생성.
ExifSubIFDDirectory directory = metadata.getDirectory(ExifSubIFDDirectory.class);
 
// 디렉토리의 태그에 해당하는 값을 가져옴.
// 이미지생성일시, 촬영기기모델명
Date originalDate = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
String modelName = directory.getString(ExifSubIFDDirectory.TAG_LENS_MODEL);

 디렉토리를 비슷한 메타데이터를 묶는 하나의 분류라고 생각하면 편하다. 위 예제는 ExifSubIFD directory에서 태그값에 따라 메타데이터를 가져온 것이다. 만약 이미지의 GPS값을 가지고 오고 싶다면, GPS directory에서 가져오면 된다. 아래 소스코드를 참고하자.




Metadata metadata = ImageMetadataReader.readMetadata(file);
GpsDirectory gpsDirectory = metadata.getDirectory(GpsDirectory.class);
 
GeoLocation geoLocation = gpsDirectory.getGeoLocation();
 
if(geoLocation != null && !geoLocation.isZero()) {
     fileinfo.setLatitude(geoLocation.getLatitude());
     fileinfo.setLatitude(geoLocation.getLongitude());
 }



 이미지가 촬영된 위치의 GPS 위,경도값을 가져오는 소스코드이다. 해당 위,경도는 지도 API(구글, 네이버, 다음 등이 제공한다.)에 바로 활용할 수 있다.



 Spring에서 파일 업로드를 구현하면 MultipartFile로 처리하는 경우가 많다. MultipartFile로 이미지 입력을 받았으면 이를 File형태로 변환하는 것이 선행되어야 할 것이다. FileOutputStream을 사용하여 아래와 같이 간단하게 처리할 수 있다.




public File convert(MultipartFile multipartFile) {    
    File file= new File(multipartFile.getOriginalFilename());
    file.createNewFile(); 
    FileOutputStream fos = new FileOutputStream(file); 
    fos.write(multipartFile.getBytes());
    fos.close(); 
    return file;
}




-끝-





출처및참고

https://drewnoakes.com/code/exif/

http://stackoverflow.com/questions/24339990/how-to-convert-a-multipart-file-to-file

http://blog.naver.com/PostView.nhn?blogId=hiake2001&logNo=140177468796




반응형
최근에 올라온 글
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함
Total
Today
Yesterday