由于项目需要对照片的EXIF信息进行处理,因此在网上搜索了一番。捣鼓出来了,写下,总结。
需要用到2个jar包,metadata-extractor-2.3.1和mediautil-1.0。这2个jar包比较好找,地址就不写了,搜索下就OK。需要注意的是,mediautil-1.0这个jar包你需要修改下。因为,项目需要修改GPS,其提供的例子后面还提供了个地址,里面有5个java文件,拿出来,在项目中建好。然后在jar包将里面5个同名的文件删除,就OK了。否则你的例子会报错,还有,项目的JDK必须是1.5,编译环境也必须是1.5哦。这2个jar包,前者只能读,不能写,后者呢可以读也可以写,但是使用没有前者方便,因此仍然保留。
下面就帖2段代码,只贴main方法了。
先是读取EXIF信息的。
- public static void main(String[] args) throws Exception {
- File jpegFile = new File( "D:\\nozip\\4.jpg" );
- Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
- Directory exif = metadata.getDirectory(ExifDirectory. class ); //这里要稍微注意下
- Iterator tags = exif.getTagIterator();
- while (tags.hasNext()) {
- Tag tag = (Tag)tags.next();
- System.out.println(tag);
- }
- }
上面写的稍微注意的地方是要注意ExifDirectory. class,因为ExifDirectory只是EXIF中大部分的参数,但是并不是所有的参数。比如要查看GPS的信息则需要GpsDirectory,而它和ExifDirectory都是继承自Directory。同样继承自Directory还有好几个,就看你需要的情况了。顺便贴下它的API 。
再下面是写EXIF信息的。
- /**
- * 将照片中的信息进行重写
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- //原文件
- InputStream fip = new BufferedInputStream( new FileInputStream( "D:\\nozip\\2.jpg" )); // No need to buffer
- LLJTran llj = new LLJTran(fip);
- try {
- llj.read(LLJTran.READ_INFO, true );
- } catch (LLJTranException e) {
- e.printStackTrace();
- }
- Exif exif = (Exif) llj.getImageInfo();
- /* Set some values directly to gps IFD */
- Entry e;
- // Set Latitude
- e = new Entry(Exif.ASCII);
- e.setValue( 0 , 'N' );
- exif.setTagValue(Exif.GPSLatitudeRef,- 1 , e, true );
- //设置具体的精度
- e = new Entry(Exif.RATIONAL);
- e.setValue( 0 , new Rational( 31 , 1 ));
- e.setValue( 1 , new Rational( 21 , 1 ));
- e.setValue( 2 , new Rational( 323 , 1 ));
- exif.setTagValue(Exif.GPSLatitude,- 1 , e, true );
- // Set Longitude
- e = new Entry(Exif.ASCII);
- e.setValue( 0 , 'E' );
- exif.setTagValue(Exif.GPSLongitudeRef,- 1 , e, true );
- //设置具体的纬度
- e = new Entry(Exif.RATIONAL);
- e.setValue( 0 , new Rational( 120 , 1 ));
- e.setValue( 1 , new Rational( 58 , 1 ));
- e.setValue( 2 , new Rational( 531 , 1 ));
- exif.setTagValue(Exif.GPSLongitude,- 1 , e, true );
- llj.refreshAppx(); // Recreate Marker Data for changes done
- //改写后的文件,文件必须存在
- OutputStream out = new BufferedOutputStream( new FileOutputStream( "D:\\nozip\\1.jpg" ));
- // Transfer remaining of image to output with new header.
- llj.xferInfo( null , out, LLJTran.REPLACE, LLJTran.REPLACE);
- fip.close();
- out.close();
- llj.freeMemory();
- }
将图片中的GPS信息进行重写后,再用上面读GPS的来读将读取不到任何信息,只能在ExifDirectoy里面才能读到了,但是都是unkown tag了,很是奇怪。但是,机器等设备还是可以读到信息的。