Android开发之使用ExifInterface获取拍照后的图片属性
本文实例讲述了Android开发之使用ExifInterface获取拍照后的图片属性。分享给大家供大家参考,具体如下:
ExifInterfaceexif=newExifInterface(file.getPath()); StringwidthStr=exif.getAttribute(ExifInterface.TAG_IMAGE_WIDTH); StringheightStr=exif.getAttribute(ExifInterface.TAG_IMAGE_LENGTH); ......
/* *Copyright(C)2007TheAndroidOpenSourceProject * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packageandroid.media; importjava.io.IOException; importjava.text.ParsePosition; importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.HashMap; importjava.util.Map; importjava.util.TimeZone; /** *ThisisaclassforreadingandwritingExiftagsinaJPEGfile. */ publicclassExifInterface{ //TheExiftagnames /**Typeisint.*/ publicstaticfinalStringTAG_ORIENTATION="Orientation"; /**TypeisString.*/ publicstaticfinalStringTAG_DATETIME="DateTime"; /**TypeisString.*/ publicstaticfinalStringTAG_MAKE="Make"; /**TypeisString.*/ publicstaticfinalStringTAG_MODEL="Model"; /**Typeisint.*/ publicstaticfinalStringTAG_FLASH="Flash"; /**Typeisint.*/ publicstaticfinalStringTAG_IMAGE_WIDTH="ImageWidth"; /**Typeisint.*/ publicstaticfinalStringTAG_IMAGE_LENGTH="ImageLength"; /**String.Formatis"num1/denom1,num2/denom2,num3/denom3".*/ publicstaticfinalStringTAG_GPS_LATITUDE="GPSLatitude"; /**String.Formatis"num1/denom1,num2/denom2,num3/denom3".*/ publicstaticfinalStringTAG_GPS_LONGITUDE="GPSLongitude"; /**TypeisString.*/ publicstaticfinalStringTAG_GPS_LATITUDE_REF="GPSLatitudeRef"; /**TypeisString.*/ publicstaticfinalStringTAG_GPS_LONGITUDE_REF="GPSLongitudeRef"; /**TypeisString.*/ publicstaticfinalStringTAG_GPS_TIMESTAMP="GPSTimeStamp"; /**TypeisString.*/ publicstaticfinalStringTAG_GPS_DATESTAMP="GPSDateStamp"; /**Typeisint.*/ publicstaticfinalStringTAG_WHITE_BALANCE="WhiteBalance"; /**Typeisrational.*/ publicstaticfinalStringTAG_FOCAL_LENGTH="FocalLength"; /**TypeisString.NameofGPSprocessingmethodusedforlocationfinding.*/ publicstaticfinalStringTAG_GPS_PROCESSING_METHOD="GPSProcessingMethod"; //ConstantsusedfortheOrientationExiftag. publicstaticfinalintORIENTATION_UNDEFINED=0; publicstaticfinalintORIENTATION_NORMAL=1; publicstaticfinalintORIENTATION_FLIP_HORIZONTAL=2;//leftrightreversedmirror publicstaticfinalintORIENTATION_ROTATE_180=3; publicstaticfinalintORIENTATION_FLIP_VERTICAL=4;//upsidedownmirror publicstaticfinalintORIENTATION_TRANSPOSE=5;//flippedabouttop-left<-->bottom-rightaxis publicstaticfinalintORIENTATION_ROTATE_90=6;//rotate90cwtorightit publicstaticfinalintORIENTATION_TRANSVERSE=7;//flippedabouttop-right<-->bottom-leftaxis publicstaticfinalintORIENTATION_ROTATE_270=8;//rotate270torightit //Constantsusedforwhitebalance publicstaticfinalintWHITEBALANCE_AUTO=0; publicstaticfinalintWHITEBALANCE_MANUAL=1; privatestaticSimpleDateFormatsFormatter; static{ System.loadLibrary("exif"); sFormatter=newSimpleDateFormat("yyyy:MM:ddHH:mm:ss"); sFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); } privateStringmFilename; privateHashMap<String,String>mAttributes; privatebooleanmHasThumbnail; //Becausetheunderlyingimplementation(jhead)usesstaticvariables, //therecanonlybeoneuseratatimeforthenativefunctions(and //theycannotkeepstateinthenativecodeacrossfunctioncalls).We //usesLocktoserializetheaccesses. privatestaticObjectsLock=newObject(); /** *ReadsExiftagsfromthespecifiedJPEGfile. */ publicExifInterface(Stringfilename)throwsIOException{ mFilename=filename; loadAttributes(); } /** *Returnsthevalueofthespecifiedtagor{@codenull}ifthere *isnosuchtagintheJPEGfile. * *@paramtagthenameofthetag. */ publicStringgetAttribute(Stringtag){ returnmAttributes.get(tag); } /** *Returnstheintegervalueofthespecifiedtag.Ifthereisnosuchtag *intheJPEGfileorthevaluecannotbeparsedasinteger,return *<var>defaultValue</var>. * *@paramtagthenameofthetag. *@paramdefaultValuethevaluetoreturnifthetagisnotavailable. */ publicintgetAttributeInt(Stringtag,intdefaultValue){ Stringvalue=mAttributes.get(tag); if(value==null)returndefaultValue; try{ returnInteger.valueOf(value); }catch(NumberFormatExceptionex){ returndefaultValue; } } /** *Returnsthedoublevalueofthespecifiedrationaltag.Ifthereisno *suchtagintheJPEGfileorthevaluecannotbeparsedasdouble,return *<var>defaultValue</var>. * *@paramtagthenameofthetag. *@paramdefaultValuethevaluetoreturnifthetagisnotavailable. */ publicdoublegetAttributeDouble(Stringtag,doubledefaultValue){ Stringvalue=mAttributes.get(tag); if(value==null)returndefaultValue; try{ intindex=value.indexOf("/"); if(index==-1)returndefaultValue; doubledenom=Double.parseDouble(value.substring(index+1)); if(denom==0)returndefaultValue; doublenum=Double.parseDouble(value.substring(0,index)); returnnum/denom; }catch(NumberFormatExceptionex){ returndefaultValue; } } /** *Setthevalueofthespecifiedtag. * *@paramtagthenameofthetag. *@paramvaluethevalueofthetag. */ publicvoidsetAttribute(Stringtag,Stringvalue){ mAttributes.put(tag,value); } /** *InitializemAttributeswiththeattributesfromthefilemFilename. * *mAttributesisaHashMapwhichstorestheExifattributesofthefile. *Thekeyisthestandardtagnameandthevalueisthetag'svalue:e.g. *Model->Nikon.Numericvaluesarestoredasstrings. * *ThisfunctionalsoinitializemHasThumbnailtoindicatewhetherthe *filehasathumbnailinside. */ privatevoidloadAttributes()throwsIOException{ //formatofstringpassedfromnativeCcode: //"attrCntattr1=valueLenvalue1attr2=value2Lenvalue2..." //example: //"4attrPtrImageLength=41024Model=6FooImageWidth=41280Make=3FOO" mAttributes=newHashMap<String,String>(); StringattrStr; synchronized(sLock){ attrStr=getAttributesNative(mFilename); } //getcount intptr=attrStr.indexOf(''); intcount=Integer.parseInt(attrStr.substring(0,ptr)); //skippastthespacebetweenitemcountandtherestoftheattributes ++ptr; for(inti=0;i<count;i++){ //extracttheattributename intequalPos=attrStr.indexOf('=',ptr); StringattrName=attrStr.substring(ptr,equalPos); ptr=equalPos+1;//skippast= //extracttheattributevaluelength intlenPos=attrStr.indexOf('',ptr); intattrLen=Integer.parseInt(attrStr.substring(ptr,lenPos)); ptr=lenPos+1;//skippasthespace //extracttheattributevalue StringattrValue=attrStr.substring(ptr,ptr+attrLen); ptr+=attrLen; if(attrName.equals("hasThumbnail")){ mHasThumbnail=attrValue.equalsIgnoreCase("true"); }else{ mAttributes.put(attrName,attrValue); } } } /** *SavethetagdataintotheJPEGfile.Thisisexpensivebecauseitinvolves *copyingalltheJPGdatafromonefiletoanotheranddeletingtheoldfile *andrenamingtheother.It'sbesttouse{@link#setAttribute(String,String)} *tosetallattributestowriteandmakeasinglecallratherthanmultiple *callsforeachattribute. */ publicvoidsaveAttributes()throwsIOException{ //formatofstringpassedtonativeCcode: //"attrCntattr1=valueLenvalue1attr2=value2Lenvalue2..." //example: //"4attrPtrImageLength=41024Model=6FooImageWidth=41280Make=3FOO" StringBuildersb=newStringBuilder(); intsize=mAttributes.size(); if(mAttributes.containsKey("hasThumbnail")){ --size; } sb.append(size+""); for(Map.Entry<String,String>iter:mAttributes.entrySet()){ Stringkey=iter.getKey(); if(key.equals("hasThumbnail")){ //thisisafakeattributenotsavedasanexiftag continue; } Stringval=iter.getValue(); sb.append(key+"="); sb.append(val.length()+""); sb.append(val); } Strings=sb.toString(); synchronized(sLock){ saveAttributesNative(mFilename,s); commitChangesNative(mFilename); } } /** *ReturnstrueiftheJPEGfilehasathumbnail. */ publicbooleanhasThumbnail(){ returnmHasThumbnail; } /** *ReturnsthethumbnailinsidetheJPEGfile,or{@codenull}ifthereisnothumbnail. *ThereturneddataisinJPEGformatandcanbedecodedusing *{@linkandroid.graphics.BitmapFactory#decodeByteArray(byte[],int,int)} */ publicbyte[]getThumbnail(){ synchronized(sLock){ returngetThumbnailNative(mFilename); } } /** *Storesthelatitudeandlongitudevalueinafloatarray.Thefirstelementis *thelatitude,andthesecondelementisthelongitude.Returnsfalseifthe *Exiftagsarenotavailable. */ publicbooleangetLatLong(floatoutput[]){ StringlatValue=mAttributes.get(ExifInterface.TAG_GPS_LATITUDE); StringlatRef=mAttributes.get(ExifInterface.TAG_GPS_LATITUDE_REF); StringlngValue=mAttributes.get(ExifInterface.TAG_GPS_LONGITUDE); StringlngRef=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); returntrue; }else{ returnfalse; } } /** *ReturnsnumberofmillisecondssinceJan.1,1970,midnight. *Returns-1ifthedatetimeinformationifnotavailable. *@hide */ publiclonggetDateTime(){ StringdateTimeString=mAttributes.get(TAG_DATETIME); if(dateTimeString==null)return-1; ParsePositionpos=newParsePosition(0); try{ Datedatetime=sFormatter.parse(dateTimeString,pos); if(datetime==null)return-1; returndatetime.getTime(); }catch(IllegalArgumentExceptionex){ return-1; } } /** *ReturnsnumberofmillisecondssinceJan.1,1970,midnightUTC. *Returns-1ifthedatetimeinformationifnotavailable. *@hide */ publiclonggetGpsDateTime(){ Stringdate=mAttributes.get(TAG_GPS_DATESTAMP); Stringtime=mAttributes.get(TAG_GPS_TIMESTAMP); if(date==null||time==null)return-1; StringdateTimeString=date+''+time; if(dateTimeString==null)return-1; ParsePositionpos=newParsePosition(0); try{ Datedatetime=sFormatter.parse(dateTimeString,pos); if(datetime==null)return-1; returndatetime.getTime(); }catch(IllegalArgumentExceptionex){ return-1; } } privatestaticfloatconvertRationalLatLonToFloat( StringrationalString,Stringref){ try{ String[]parts=rationalString.split(","); String[]pair; pair=parts[0].split("/"); intdegrees=(int)(Float.parseFloat(pair[0].trim()) /Float.parseFloat(pair[1].trim())); pair=parts[1].split("/"); intminutes=(int)((Float.parseFloat(pair[0].trim()) /Float.parseFloat(pair[1].trim()))); pair=parts[2].split("/"); floatseconds=Float.parseFloat(pair[0].trim()) /Float.parseFloat(pair[1].trim()); floatresult=degrees+(minutes/60F)+(seconds/(60F*60F)); if((ref.equals("S")||ref.equals("W"))){ return-result; } returnresult; }catch(RuntimeExceptionex){ //ifforwhateverreasonwecan'tparsethelatlongthenreturn //null return0f; } } privatenativebooleanappendThumbnailNative(StringfileName, StringthumbnailFileName); privatenativevoidsaveAttributesNative(StringfileName, StringcompressedAttributes); privatenativeStringgetAttributesNative(StringfileName); privatenativevoidcommitChangesNative(StringfileName); privatenativebyte[]getThumbnailNative(StringfileName); }
更多关于Android开发相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》及《Android图形与图像处理技巧总结》
希望本文所述对大家Android程序设计有所帮助。