Java获取照片EXIF信息(二)

2014-11-24 11:03:44 · 作者: · 浏览: 7
ure
[Exif] White Balance - Auto white balance
[Exif] Scene Capture Type - Standard
[Exif] Sharpness - None
[Exif] Subject Distance Range - Unknown
[Exif] Compression - JPEG (old-style)
[Exif] Thumbnail Offset - 1252 bytes
[Exif] Thumbnail Length - 7647 bytes
[Exif] Thumbnail Data - [7647 bytes of thumbnail data]
从这个执行的结果我们可以看出该照片是在2005年05月13日 22时18分49秒拍摄的,拍摄用的相机型号是富士的FinePix A205S,曝光时间是1/60秒,光圈值F3,焦距5.5毫米,ISO值为320等等。
你也可以直接指定读取其中任意参数的值,ExifDirectory类中定义了很多以TAG_开头的整数常量,这些常量代表特定的一个参数值,例如我们要读取相机的型号,我们可以用下面代码来获取。
[java]
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
Directory exif = metadata.getDirectory(ExifDirectory.class);
String model = exif.getString(ExifDirectory.TAG_MODEL);
上述提到的是如何获取照片的EXIF信息,其中包含一个很重要的信息就是——拍摄方向。例如上面例子所用的图片的拍摄方向是:Orientation - Top, left side (Horizontal / normal)。我们在拍照的时候经常会根据场景的不同来选择相机的方向,例如拍摄一颗高树,我们会把相机竖着拍摄,使景物刚好适合整个取景框,但是这样得到的图片如果用普通的图片 浏览器看便是倒着的,需要调整角度才能得到一个正常的图像,有如下面一张照片。
这张图片正常的情况下需要向左调整90度,也就是顺时针旋转270度才适合观看。通过读取该图片的EXIF信息,我们得到关于拍摄方向的这样一个结果:[Exif] Orientation - Left side, bottom (Rotate 270 CW)。而直接读取ExitDirectory.TAG_ORIENTATION标签的值是8。我们再来看这个项目是如何来定义这些返回值的,打开源码包中的ExifDescriptor类的getOrientationDescription方法,该方法代码如下:
[java]
public String getOrientationDescription() throws MetadataException
{
if (!_directory.containsTag(ExifDirectory.TAG_ORIENTATION)) return null;
int orientation = _directory.getInt(ExifDirectory.TAG_ORIENTATION);
switch (orientation) {
case 1: return "Top, left side (Horizontal / normal)";
case 2: return "Top, right side (Mirror horizontal)";
case 3: return "Bottom, right side (Rotate 180)";
case 4: return "Bottom, left side (Mirror vertical)";
case 5: return "Left side, top (Mirror horizontal and rotate 270 CW)";
case 6: return "Right side, top (Rotate 90 CW)";
case 7: return "Right side, bottom (Mirror horizontal and rotate 90 CW)";
case 8: return "Left side, bottom (Rotate 270 CW)";
default:
return String.valueOf(orientation);
}
}
从这个方法我们可以清楚看到各个返回值的意思,如此我们便可以根据实际的返回值来对图像进行旋转或者是镜像处理了。在这个例子中我们需要将图片顺时针旋转270度,或者是逆时针旋转90度方可得到正常的图片。
虽然图片的旋转不在本文范畴内,但为了善始善终,下面给出代码用以旋转图片,其他的关于图片的镜像等处理读者可以依此类推。
[java]
String path = "D:\\TEST.JPG";
File img = new File(path);
BufferedImage old_img = (BufferedImage)ImageIO.read(img);
int w = old_img.getWidth();
int h = old_img.getHeight();
BufferedImage new_img = new BufferedImage(h,w,BufferedImage.TYPE_INT_BGR);
Graphics2D g2d =new_img.createGraphics();
AffineTransform origXform = g2d.getTransform();
AffineTransform newXform = (AffineTransform)(origXform.clone());
// center of rotation is center of the panel
double xRot = w/2.0;
newXform.rotate(Math.toRadians(270.0), xRot, xRot); //旋转270度
g2d.setTransform(newXform);
// draw image centered in panel
g2d.drawImage(old_img, 0, 0, null);
// Reset to Original
g2d.setTransform(origXform);
//写到新的文件
FileOutputStream out = new FileOutputStream("D:\\test2.jpg");
try{
ImageIO.write(new_img, "JPG", out);
}finally{
out.close();