当前位置: 首页 > 编程文章 >

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

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

作者:周景时间:2025-09-17 10:17:46浏览:326

在Android开发中,通过ExifInterface类可以读取图片文件的EXIF信息。本文介绍如何使用该API获取拍照后图片的宽度和高度等属性,并提供相关代码示例供参考。

本文目录展开

使用ExifInterface获取图片属性

本内容分享了在Android应用中利用ExifInterface类读取图像文件元数据的方法,旨在为开发者提供实用的技术参考与实现思路。


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


/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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;
/**
 * This is a class for reading and writing Exif tags in a JPEG file.
 */
public class ExifInterface {
  // The Exif tag names
  /** Type is int. */
  public static final String TAG_ORIENTATION = "Orientation";
  /** Type is String. */
  public static final String TAG_DATETIME = "DateTime";
  /** Type is String. */
  public static final String TAG_MAKE = "Make";
  /** Type is String. */
  public static final String TAG_MODEL = "Model";
  /** Type is int. */
  public static final String TAG_FLASH = "Flash";
  /** Type is int. */
  public static final String TAG_IMAGE_WIDTH = "ImageWidth";
  /** Type is int. */
  public static final String TAG_IMAGE_LENGTH = "ImageLength";
  /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */
  public static final String TAG_GPS_LATITUDE = "GPSLatitude";
  /** String. Format is "num1/denom1,num2/denom2,num3/denom3". */
  public static final String TAG_GPS_LONGITUDE = "GPSLongitude";
  /** Type is String. */
  public static final String TAG_GPS_LATITUDE_REF = "GPSLatitudeRef";
  /** Type is String. */
  public static final String TAG_GPS_LONGITUDE_REF = "GPSLongitudeRef";
  /** Type is String. */
  public static final String TAG_GPS_TIMESTAMP = "GPSTimeStamp";
  /** Type is String. */
  public static final String TAG_GPS_DATESTAMP = "GPSDateStamp";
  /** Type is int. */
  public static final String TAG_WHITE_BALANCE = "WhiteBalance";
  /** Type is rational. */
  public static final String TAG_FOCAL_LENGTH = "FocalLength";
  /** Type is String. Name of GPS processing method used for location finding. */
  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 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();
  /**
   * Reads Exif tags from the specified JPEG file.
   */
  public ExifInterface(String filename) throws IOException {
    mFilename = filename;
    loadAttributes();
  }
  /**
   * Returns the value of the specified tag or {@code null} if there
   * is no such tag in the JPEG file.
   *
   * @param tag the name of the tag.
   */
  public String getAttribute(String tag) {
    return mAttributes.get(tag);
  }
  /**
   * Returns the integer value of the specified tag. If there is no such tag
   * in the JPEG file or the value cannot be parsed as integer, return
   * defaultValue.
   *
   * @param tag the name of the tag.
   * @param defaultValue the value to return if the tag is not available.
   */
  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;
    }
  }
  /**
   * Returns the double value of the specified rational tag. If there is no
   * such tag in the JPEG file or the value cannot be parsed as double, return
   * defaultValue.
   *
   * @param tag the name of the tag.
   * @param defaultValue the value to return if the tag is not available.
   */
  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;
    }
  }
  /**
   * Set the value of the specified tag.
   *
   * @param tag the name of the tag.
   * @param value the value of the tag.
   */
  public void setAttribute(String tag, String value) {
    mAttributes.put(tag, value);
  }
  /**
   * Initialize mAttributes with the attributes from the file mFilename.
   *
   * mAttributes is a HashMap which stores the Exif attributes of the file.
   * The key is the standard tag name and the value is the tag's value: e.g.
   * Model -> Nikon. Numeric values are stored as strings.
   *
   * This function also initialize mHasThumbnail to indicate whether the
   * file has a thumbnail inside.
   */
  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 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);
      }
    }
  }
  /**
   * Save the tag data into the JPEG file. This is expensive because it involves
   * copying all the JPG data from one file to another and deleting the old file
   * and renaming the other. It's best to use {@link #setAttribute(String,String)}
   * to set all attributes to write and make a single call rather than multiple
   * calls for each attribute.
   */
  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 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);
    }
  }
  /**
   * Returns true if the JPEG file has a thumbnail.
   */
  public boolean hasThumbnail() {
    return mHasThumbnail;
  }
  /**
   * Returns the thumbnail inside the JPEG file, or {@code null} if there is no thumbnail.
   * The returned data is in JPEG format and can be decoded using
   * {@link android.graphics.BitmapFactory#decodeByteArray(byte[],int,int)}
   */
  public byte[] getThumbnail() {
    synchronized (sLock) {
      return getThumbnailNative(mFilename);
    }
  }
  /**
   * Stores the latitude and longitude value in a float array. The first element is
   * the latitude, and the second element is the longitude. Returns false if the
   * Exif tags are not available.
   */
  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;
    }
  }
  /**
   * Returns number of milliseconds since Jan. 1, 1970, midnight.
   * Returns -1 if the date time information if not available.
   * @hide
   */
  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;
    }
  }
  /**
   * Returns number of milliseconds since Jan. 1, 1970, midnight UTC.
   * Returns -1 if the date time information if not available.
   * @hide
   */
  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程序设计的技巧能对大家有所帮助。

上一篇
Java读取图片EXIF信息的方法

本文介绍如何使用Java语言读取JPG图片的EXIF信息。通过Drew Noakes开发的metadata-extractor库,可以获取相机品牌、型号、拍摄时间、光圈、快门速度及ISO等详细参数。文章提供了完整的代码示例,展示如何遍历所有标签或仅读取特定字段,并说明了并非所有JPG文件都包含此类数据。

下一篇
Android中Exif格式解析与Camera拍照流程优化

Exif(Exchangeable Image File)是嵌入在JPEG文件头中的拍摄参数信息,包含光圈、快门、GPS等数据。在Android Froyo (2.2) 架构中,Exif写入由HAL层处理,若底层未正确写入且上层未校验,会导致图片Orientation丢失。通过对比应用层传入的方向参数与底层返回的Exif值,可在应用层利用ExifInterface进行修正,确保图片显示方向正确。

相关文章

更多
Android上传图片到PHP的过程详解

本文详细记录了解决Android端上传图片出现连接超时错误的过程。通过排查发现并非代码逻辑问题,而是本地测试环境配置不当及远程服务器性能瓶颈所致。文章提供了使用WampServer搭建本地PHP环境的完整步骤,包括Apache权限设置和phpMyAdmin访问修复,并给出了Android端使用HttpURLConnection或类似库上传图片的关键代码片段,帮助开发者快速定位网络请求中的常见陷阱。

2025.11.23 688
Android基于SQLite实现登录注册功能详解

本文介绍在Android应用中通过SQLite数据库实现用户登录与注册功能的完整方案。核心逻辑包含使用正则表达式校验账号密码格式,利用SQLiteDatabase进行数据的增删改查,以及通过Intent在不同Activity间传递数据。代码展示了从数据库创建、实体类定义到界面交互的具体实现细节,帮助开发者快速构建基础的身份验证模块。

2026.02.26 687
Android中HttpPost与HttpGet请求的使用方法详解

本文介绍Android中使用DefaultHttpClient发起HttpPost和HttpGet请求的具体实现。HttpPost通过UrlEncodedFormEntity模拟表单提交参数,适用于数据上传;HttpGet直接在URL后拼接参数,适用于数据获取。两者均通过execute方法执行并返回HttpResponse,需检查状态码200以确认服务端响应成功,并利用EntityUtils解析返回结果。

2026.05.13 628

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。