Android Development uses Exifinterface to get picture properties after a photo _android

Source: Internet
Author: User
Tags int size tag name

This example describes the Android development using Exifinterface to get picture properties after taking pictures. Share to everyone for your reference, specific as follows:

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 "Licen
 Se ");
 * You could not use this file, except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by APPL Icable or agreed to in writing, software * Distributed under the License was distributed on ' as is ' basis, * witho
 UT warranties or CONDITIONS of any KIND, either express OR implied.
 * 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;
 /** * 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. The Format is "num1/denom1,num2/denom2,num3/denom3".
  * * public static final String tag_gps_latitude = "Gpslatitude"; /** String. The 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 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 is 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 to parsed as Integer, return * <var>defaultvalu
   E</var>.
   * @param tag The name of the tag.
   * @param defaultvalue the value to return if the ' 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 to parsed as double, return * <var>defaultvalue
   </var>.
   * @param tag The name of the tag.
   * @param defaultvalue the value to return if the ' 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 is 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, 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); }}/** * Save the tag data into the JPEG file. This is expensive because it involves * copying "all" 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 th
   An multiple * calls for each attribute. */public void saveattributes () throws IOException {//format of string passed to native C code://ATTRCNT at Tr1=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 was a fake attribute not saved as a 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 decoded using * {@link Android.graphics.bitmapfactory#decodebytearray ( Byte[],int,int)} */public byte[] GetThumbnail () {synchronized (Slock) {return getthumbnailnative (Mfilena
    ME); }/** * Stores the latitude and longitude value in a float array. 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. 1, 1970, midnight.
   * RETURNS-1 If the date 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. 1, 1970, Midnight UTC.
   * RETURNS-1 If the date 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 {Stri
      ng [] 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;
      The 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);

 }

For more information about Android development interested readers can view the site topics: "Android Development Introduction and Advanced Course" and "Android graphics and image processing skills summary"

I hope this article will help you with the Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.