iis服务器助手广告广告
返回顶部
首页 > 资讯 > 移动开发 >Android开发之使用ExifInterface获取拍照后的图片属性
  • 885
分享到

Android开发之使用ExifInterface获取拍照后的图片属性

属性图片android开发Android 2022-06-06 09:06:03 885人浏览 八月长安
摘要

本文实例讲述了Android开发之使用ExifInterface获取拍照后的图片属性。分享给大家供大家参考,具体如下: ExifInterface exif = new Ex

本文实例讲述了Android开发之使用ExifInterface获取拍照后的图片属性。分享给大家供大家参考,具体如下:


ExifInterface exif = new ExifInterface(file.getPath());
String widthStr = exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH);
String heightStr = exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH);
......


package android.media;
import java.io.IOException;
import java.text.ParsePosition;
import java.text.SimpleDateFORMat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

public class ExifInterface {
  // The Exif tag names
  
  public static final String TAG_ORIENTATION = "Orientation";
  
  public static final String TAG_DATETIME = "DateTime";
  
  public static final String TAG_MAKE = "Make";
  
  public static final String TAG_MODEL = "Model";
  
  public static final String TAG_FLASH = "Flash";
  
  public static final String TAG_IMAGE_WIDTH = "ImageWidth";
  
  public static final String TAG_IMAGE_LENGTH = "ImageLength";
  
  public static final String TAG_GPS_LATITUDE = "GPSLatitude";
  
  public static final String TAG_GPS_LONgitUDE = "GPSLongitude";
  
  public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
  
  public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
  
  public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
  
  public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
  
  public static final String TAG_WHITE_BALANCE = "WhiteBalance";
  
  public static final String TAG_FOCAL_LENGTH = "FocalLength";
  
  public static final String TAG_GPS_PROCESSING_METHOD = "GPSProcessingMethod";
  // Constants used for the Orientation Exif tag.
  public static final int ORIENTATION_UNDEFINED = 0;
  public static final int ORIENTATION_NORMAL = 1;
  public static final int ORIENTATION_FLIP_HORIZONTAL = 2; // left right reversed mirror
  public static final int ORIENTATION_ROTATE_180 = 3;
  public static final int ORIENTATION_FLIP_VERTICAL = 4; // upside down mirror
  public static final int ORIENTATION_TRANSPOSE = 5; // flipped about top-left <--> bottom-right axis
  public static final int ORIENTATION_ROTATE_90 = 6; // rotate 90 cw to right it
  public static final int ORIENTATION_TRANSVERSE = 7; // flipped about top-right <--> bottom-left axis
  public static final int ORIENTATION_ROTATE_270 = 8; // rotate 270 to right it
  // Constants used for white balance
  public static final int WHITEBALANCE_AUTO = 0;
  public static final int WHITEBALANCE_MANUAL = 1;
  private static SimpleDateFormat sFormatter;
  static {
    System.loadLibrary("exif");
    sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
    sFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
  }
  private String mFilename;
  private HashMap<String, String> mAttributes;
  private boolean mHasThumbnail;
  // Because the underlying implementation (jhead) uses static variables,
  // there can only be one user at a time for the native functions (and
  // they cannot keep state in the native code across function calls). We
  // use sLock to serialize the accesses.
  private static Object sLock = new Object();
  
  public ExifInterface(String filename) throws IOException {
    mFilename = filename;
    loadAttributes();
  }
  
  public String getAttribute(String tag) {
    return mAttributes.get(tag);
  }
  
  public int getAttributeInt(String tag, int defaultValue) {
    String value = mAttributes.get(tag);
    if (value == null) return defaultValue;
    try {
      return Integer.valueOf(value);
    } catch (NumberFormatException ex) {
      return defaultValue;
    }
  }
  
  public double getAttributeDouble(String tag, double defaultValue) {
    String value = mAttributes.get(tag);
    if (value == null) return defaultValue;
    try {
      int index = value.indexOf("/");
      if (index == -1) return defaultValue;
      double denom = Double.parseDouble(value.substring(index + 1));
      if (denom == 0) return defaultValue;
      double num = Double.parseDouble(value.substring(0, index));
      return num / denom;
    } catch (NumberFormatException ex) {
      return defaultValue;
    }
  }
  
  public void setAttribute(String tag, String value) {
    mAttributes.put(tag, value);
  }
  
  private void loadAttributes() throws IOException {
    // format of string passed from native C code:
    // "attrCnt attr1=valueLen value1attr2=value2Len value2..."
    // example:
    // "4 attrPtr ImageLength=4 1024Model=6 FooImageWidth=4 1280Make=3 FOO"
    mAttributes = new HashMap<String, String>();
    String attrStr;
    synchronized (sLock) {
      attrStr = getAttributesNative(mFilename);
    }
    // get count
    int ptr = attrStr.indexOf(' ');
    int count = Integer.parseInt(attrStr.substring(0, ptr));
    // skip past the space between item count and the rest of the attributes
    ++ptr;
    for (int i = 0; i < count; i++) {
      // extract the attribute name
      int equalPos = attrStr.indexOf('=', ptr);
      String attrName = attrStr.substring(ptr, equalPos);
      ptr = equalPos + 1;   // skip past =
      // extract the attribute value length
      int lenPos = attrStr.indexOf(' ', ptr);
      int attrLen = Integer.parseInt(attrStr.substring(ptr, lenPos));
      ptr = lenPos + 1;    // skip pas the space
      // extract the attribute value
      String attrValue = attrStr.substring(ptr, ptr + attrLen);
      ptr += attrLen;
      if (attrName.equals("hasThumbnail")) {
        mHasThumbnail = attrValue.equalsIgnoreCase("true");
      } else {
        mAttributes.put(attrName, attrValue);
      }
    }
  }
  
  public void saveAttributes() throws IOException {
    // format of string passed to native C code:
    // "attrCnt attr1=valueLen value1attr2=value2Len value2..."
    // example:
    // "4 attrPtr ImageLength=4 1024Model=6 FooImageWidth=4 1280Make=3 FOO"
    StringBuilder sb = new StringBuilder();
    int size = mAttributes.size();
    if (mAttributes.containsKey("hasThumbnail")) {
      --size;
    }
    sb.append(size + " ");
    for (Map.Entry<String, String> iter : mAttributes.entrySet()) {
      String key = iter.geTKEy();
      if (key.equals("hasThumbnail")) {
        // this is a fake attribute not saved as an exif tag
        continue;
      }
      String val = iter.getValue();
      sb.append(key + "=");
      sb.append(val.length() + " ");
      sb.append(val);
    }
    String s = sb.toString();
    synchronized (sLock) {
      saveAttributesNative(mFilename, s);
      commitChangesNative(mFilename);
    }
  }
  
  public boolean hasThumbnail() {
    return mHasThumbnail;
  }
  
  public byte[] getThumbnail() {
    synchronized (sLock) {
      return getThumbnailNative(mFilename);
    }
  }
  
  public boolean getLatLong(float output[]) {
    String latValue = mAttributes.get(ExifInterface.TAG_GPS_LATITUDE);
    String latRef = mAttributes.get(ExifInterface.TAG_GPS_LATITUDE_REF);
    String lngValue = mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE);
    String lngRef = mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE_REF);
    if (latValue != null && latRef != null && lngValue != null && lngRef != null) {
      output[0] = convertRationalLatLonToFloat(latValue, latRef);
      output[1] = convertRationalLatLonToFloat(lngValue, lngRef);
      return true;
    } else {
      return false;
    }
  }
  
  public long getDateTime() {
    String dateTimeString = mAttributes.get(TAG_DATETIME);
    if (dateTimeString == null) return -1;
    ParsePosition pos = new ParsePosition(0);
    try {
      Date datetime = sFormatter.parse(dateTimeString, pos);
      if (datetime == null) return -1;
      return datetime.getTime();
    } catch (IllegalArgumentException ex) {
      return -1;
    }
  }
  
  public long getGpsDateTime() {
    String date = mAttributes.get(TAG_GPS_DATESTAMP);
    String time = mAttributes.get(TAG_GPS_TIMESTAMP);
    if (date == null || time == null) return -1;
    String dateTimeString = date + ' ' + time;
    if (dateTimeString == null) return -1;
    ParsePosition pos = new ParsePosition(0);
    try {
      Date datetime = sFormatter.parse(dateTimeString, pos);
      if (datetime == null) return -1;
      return datetime.getTime();
    } catch (IllegalArgumentException ex) {
      return -1;
    }
  }
  private static float convertRationalLatLonToFloat(
      String rationalString, String ref) {
    try {
      String [] parts = rationalString.split(",");
      String [] pair;
      pair = parts[0].split("/");
      int degrees = (int) (Float.parseFloat(pair[0].trim())
          / Float.parseFloat(pair[1].trim()));
      pair = parts[1].split("/");
      int minutes = (int) ((Float.parseFloat(pair[0].trim())
          / Float.parseFloat(pair[1].trim())));
      pair = parts[2].split("/");
      float seconds = Float.parseFloat(pair[0].trim())
          / Float.parseFloat(pair[1].trim());
      float result = degrees + (minutes / 60F) + (seconds / (60F * 60F));
      if ((ref.equals("S") || ref.equals("W"))) {
        return -result;
      }
      return result;
    } catch (RuntimeException ex) {
      // if for whatever reason we can't parse the lat long then return
      // null
      return 0f;
    }
  }
  private native boolean appendThumbnailNative(String fileName,
      String thumbnailFileName);
  private native void saveAttributesNative(String fileName,
      String compressedAttributes);
  private native String getAttributesNative(String fileName);
  private native void commitChangesNative(String fileName);
  private native byte[] getThumbnailNative(String fileName);
}

更多关于Android开发相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》及《Android图形与图像处理技巧总结

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:Android启动相机拍照并返回图片android图像绘制(六)获取本地图片或拍照图片等图片资源Android实现拍照、选择图片并裁剪图片功能Android拍照得到全尺寸图片并进行压缩Android手机拍照或选取图库图片作为头像Android实现从本地图库/相机拍照后裁剪图片并设置头像android完美实现 拍照 选择图片 剪裁等代码分享Android拍照裁剪图片Android拍照和获取相册图片Android实现拍照及图片显示效果


--结束END--

本文标题: Android开发之使用ExifInterface获取拍照后的图片属性

本文链接: https://www.lsjlt.com/news/25825.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作