9

Android Bitmap小技巧 - 压缩时保留图片的Exif信息

 3 years ago
source link: http://yuanfentiank789.github.io/2017/04/11/exif/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Android Bitmap小技巧

大家都知道,相机在照相时是会为照片生成Exif,里面包含有拍照时间、图片尺寸、旋转角度、GPS定位等信息,有时候,我们的APP在展示图片的时候需要获得并展现这些信息。

image

但是在android中,当我们将手机本地照片decod为bitmap后,bitmap对象中是没有这些Exif信息的,而一般情况下用户拍照后将照片上传是肯定不会让上传原图的,都会对图片进行适当压缩。无论是Bitmap.compress还是BitmapFactory inSampleSize压缩,Exif信息都会丢失,这显然不是我们想要的结果,我们需要将原图的Exif信息写入新的压缩后的图片中,那么怎么做呢,其实Exif信息是存储在于图片的文件头信息中,它拥有自己规定好的标识符,我们可以按照其标准使用OutputStream写入,但是这样当然非常的麻烦,而android中已经为我们提供了便捷的方法,那就是使用ExifInterface。

提供一个我写好的工具方法

public static void saveExif(String oldFilePath, String newFilePath) throws Exception {
    ExifInterface oldExif=new ExifInterface(oldFilePath);
    ExifInterface newExif=new ExifInterface(newFilePath);
    Class<ExifInterface> cls = ExifInterface.class;
    Field[] fields = cls.getFields();
    for (int i = 0; i < fields.length; i++) {
        String fieldName = fields[i].getName();
        if (!TextUtils.isEmpty(fieldName) && fieldName.startsWith("TAG")) {
            String fieldValue = fields[i].get(cls).toString();
            String attribute = oldExif.getAttribute(fieldValue);
            if (attribute != null) {
                newExif.setAttribute(fieldValue, attribute);
            }
        }
    }
    newExif.saveAttributes();
}

传入原图的path和压缩后图片的path即可,方法内容很简单,就是把原图的Exif信息一项一项的读出来再设置进压缩后的图片文件中,但是因为我们事先并不知道原图都有哪些Exif信息,而ExifInterface中也没有提供任何方法遍历这些信息,所以我用了反射拿到ExifInterface中所有的Field进行遍历,只要这个Field的名字是以TAG开头的都是Exif信息标识符,具体大家可以自己到ExifInterface中去看,这样就可以在一个循环内就把原图的Exif写入压缩后的新图文件中了。

这里还有一个小问题,就是压缩后的图片必须是JPEG格式的,只有JPEG格式图片支持写入Exif,这点在ExifInterface saveAttributes()方法注释第一句就有提到:

Save the tag data into the JPEG file..........................以下略

最后推荐一个查看图片exif信息的软件: https://play.google.com/store/apps/details?id=com.mikufu_works.exifviewer



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK