android读取sd卡图片并进行缩放操作
16lz
2021-01-26
在Android中对大图片进行缩放真的很不尽如人意,不知道是不是我的方法不对。下面我列出3种对图片缩放的方法,并给出相应速度。请高人指教。
第一种是BitmapFactory和BitmapFactory.Options。
首先,BitmapFactory.Options有几个Fields很有用:
inJustDecodeBounds:If set to true, the decoder will return null (no bitmap), but the out...
也就是说,当inJustDecodeBounds设成true时,bitmap并不加载到内存,这样效率很高哦。而这时,你可以获得bitmap的高、宽等信息。
outHeight:The resulting height of the bitmap, set independent of the state of inJustDecodeBounds.
outWidth:The resulting width of the bitmap, set independent of the state of inJustDecodeBounds.
看到了吧,上面3个变量是相关联的哦。
inSampleSize : If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.
这就是用来做缩放比的。这里有个技巧:
inSampleSize=(outHeight/Height+outWidth/Width)/2
实践证明,这样缩放出来的图片还是很好的。
最后用BitmapFactory.decodeFile(path, options)生成。
由于只是对bitmap加载到内存一次,所以效率比较高。解析速度快。
第二种是使用Bitmap加Matrix来缩放。
[java] view plain copy
ThumbnailUtils源码:
[java] view plain copy
第一种是BitmapFactory和BitmapFactory.Options。
首先,BitmapFactory.Options有几个Fields很有用:
inJustDecodeBounds:If set to true, the decoder will return null (no bitmap), but the out...
也就是说,当inJustDecodeBounds设成true时,bitmap并不加载到内存,这样效率很高哦。而这时,你可以获得bitmap的高、宽等信息。
outHeight:The resulting height of the bitmap, set independent of the state of inJustDecodeBounds.
outWidth:The resulting width of the bitmap, set independent of the state of inJustDecodeBounds.
看到了吧,上面3个变量是相关联的哦。
inSampleSize : If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.
这就是用来做缩放比的。这里有个技巧:
inSampleSize=(outHeight/Height+outWidth/Width)/2
实践证明,这样缩放出来的图片还是很好的。
最后用BitmapFactory.decodeFile(path, options)生成。
由于只是对bitmap加载到内存一次,所以效率比较高。解析速度快。
第二种是使用Bitmap加Matrix来缩放。
首先要获得原bitmap,再从原bitmap的基础上生成新图片。这样效率很低。
第三种是用2.2新加的类ThumbnailUtils来做。
让我们新看看这个类,从API中来看,此类就三个静态方法:createVideoThumbnail、extractThumbnail(Bitmap source, int width, int height, int options)、extractThumbnail(Bitmap source, int width, int height)。
我这里使用了第三个方法。再看看它的源码,下面会附上。是上面我们用到的BitmapFactory.Options和Matrix等经过人家一阵加工而成。
效率好像比第二种方法高一点点。
下面是我的例子:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ImageView
- android:id="@+id/imageShow"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <ImageView
- android:id="@+id/image2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- </LinearLayout>
[java] view plain copy
- packagecom.linc.ResolvePicture;
- importjava.io.File;
- importjava.io.FileNotFoundException;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- importandroid.app.Activity;
- importandroid.graphics.Bitmap;
- importandroid.graphics.BitmapFactory;
- importandroid.graphics.Matrix;
- importandroid.graphics.drawable.BitmapDrawable;
- importandroid.graphics.drawable.Drawable;
- importandroid.media.ThumbnailUtils;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.widget.ImageView;
- importandroid.widget.TextView;
- publicclassResolvePictureextendsActivity{
- privatestaticStringtag="ResolvePicture";
- DrawablebmImg;
- ImageViewimView;
- ImageViewimView2;
- TextViewtext;
- StringtheTime;
- longstart,stop;
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text=(TextView)findViewById(R.id.text);
- imView=(ImageView)findViewById(R.id.imageShow);
- imView2=(ImageView)findViewById(R.id.image2);
- Bitmapbitmap=BitmapFactory.decodeResource(getResources(),
- R.drawable.pic);
- start=System.currentTimeMillis();
- //imView.setImageDrawable(resizeImage(bitmap,300,100));
- imView2.setImageDrawable(resizeImage2("/sdcard/2.jpeg",200,100));
- stop=System.currentTimeMillis();
- StringtheTime=String.format("\n1iterative:(%dmsec)",
- stop-start);
- start=System.currentTimeMillis();
- imView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap,200,100));//2.2才加进来的新类,简单易用
- //imView.setImageDrawable(resizeImage(bitmap,30,30));
- stop=System.currentTimeMillis();
- theTime+=String.format("\n2iterative:(%dmsec)",
- stop-start);
- text.setText(theTime);
- }
- //使用Bitmap加Matrix来缩放
- publicstaticDrawableresizeImage(Bitmapbitmap,intw,inth)
- {
- BitmapBitmapOrg=bitmap;
- intwidth=BitmapOrg.getWidth();
- intheight=BitmapOrg.getHeight();
- intnewWidth=w;
- intnewHeight=h;
- floatscaleWidth=((float)newWidth)/width;
- floatscaleHeight=((float)newHeight)/height;
- Matrixmatrix=newMatrix();
- matrix.postScale(scaleWidth,scaleHeight);
- //ifyouwanttorotatetheBitmap
- //matrix.postRotate(45);
- BitmapresizedBitmap=Bitmap.createBitmap(BitmapOrg,0,0,width,
- height,matrix,true);
- returnnewBitmapDrawable(resizedBitmap);
- }
- //使用BitmapFactory.Options的inSampleSize参数来缩放
- publicstaticDrawableresizeImage2(Stringpath,
- intwidth,intheight)
- {
- BitmapFactory.Optionsoptions=newBitmapFactory.Options();
- options.inJustDecodeBounds=true;//不加载bitmap到内存中
- BitmapFactory.decodeFile(path,options);
- intoutWidth=options.outWidth;
- intoutHeight=options.outHeight;
- options.inDither=false;
- options.inPreferredConfig=Bitmap.Config.ARGB_8888;
- options.inSampleSize=1;
- if(outWidth!=0&&outHeight!=0&&width!=0&&height!=0)
- {
- intsampleSize=(outWidth/width+outHeight/height)/2;
- Log.d(tag,"sampleSize="+sampleSize);
- options.inSampleSize=sampleSize;
- }
- options.inJustDecodeBounds=false;
- returnnewBitmapDrawable(BitmapFactory.decodeFile(path,options));
- }
- //图片保存
- privatevoidsaveThePicture(Bitmapbitmap)
- {
- Filefile=newFile("/sdcard/2.jpeg");
- try
- {
- FileOutputStreamfos=newFileOutputStream(file);
- if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos))
- {
- fos.flush();
- fos.close();
- }
- }
- catch(FileNotFoundExceptione1)
- {
- e1.printStackTrace();
- }
- catch(IOExceptione2)
- {
- e2.printStackTrace();
- }
- }
- }
ThumbnailUtils源码:
[java] view plain copy
- /*
- *Copyright(C)2009TheAndroidOpenSourceProject
- *
- *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;
- importandroid.content.ContentResolver;
- importandroid.content.ContentUris;
- importandroid.content.ContentValues;
- importandroid.database.Cursor;
- importandroid.graphics.Bitmap;
- importandroid.graphics.BitmapFactory;
- importandroid.graphics.Canvas;
- importandroid.graphics.Matrix;
- importandroid.graphics.Rect;
- importandroid.media.MediaMetadataRetriever;
- importandroid.media.MediaFile.MediaFileType;
- importandroid.net.Uri;
- importandroid.os.ParcelFileDescriptor;
- importandroid.provider.BaseColumns;
- importandroid.provider.MediaStore.Images;
- importandroid.provider.MediaStore.Images.Thumbnails;
- importandroid.util.Log;
- importjava.io.FileInputStream;
- importjava.io.FileDescriptor;
- importjava.io.IOException;
- importjava.io.OutputStream;
- /**
- *Thumbnailgenerationroutinesformediaprovider.
- */
- publicclassThumbnailUtils{
- privatestaticfinalStringTAG="ThumbnailUtils";
- /*Maximumpixelssizeforcreatedbitmap.*/
- privatestaticfinalintMAX_NUM_PIXELS_THUMBNAIL=512*384;
- privatestaticfinalintMAX_NUM_PIXELS_MICRO_THUMBNAIL=128*128;
- privatestaticfinalintUNCONSTRAINED=-1;
- /*Optionsusedinternally.*/
- privatestaticfinalintOPTIONS_NONE=0x0;
- privatestaticfinalintOPTIONS_SCALE_UP=0x1;
- /**
- *Constantusedtoindicateweshouldrecycletheinputin
- *{@link#extractThumbnail(Bitmap,int,int,int)}unlesstheoutputistheinput.
- */
- publicstaticfinalintOPTIONS_RECYCLE_INPUT=0x2;
- /**
- *Constantusedtoindicatethedimensionofminithumbnail.
- *@hideOnlyusedbymediaframeworkandmediaproviderinternally.
- */
- publicstaticfinalintTARGET_SIZE_MINI_THUMBNAIL=320;
- /**
- *Constantusedtoindicatethedimensionofmicrothumbnail.
- *@hideOnlyusedbymediaframeworkandmediaproviderinternally.
- */
- publicstaticfinalintTARGET_SIZE_MICRO_THUMBNAIL=96;
- /**
- *ThismethodfirstexaminesifthethumbnailembeddedinEXIFisbiggerthanourtarget
- *size.Ifnot,thenit'llcreateathumbnailfromoriginalimage.Duetoefficiency
- *consideration,wewanttoletMediaThumbRequestavoidcallingthismethodtwicefor
- *bothkinds,soitonlyrequestsforMICRO_KINDandsetsaveImagetotrue.
- *
- *Thismethodalwaysreturnsa"squarethumbnail"forMICRO_KINDthumbnail.
- *
- *@paramfilePaththepathofimagefile
- *@paramkindcouldbeMINI_KINDorMICRO_KIND
- *@returnBitmap
- *
- *@hideThismethodisonlyusedbymediaframeworkandmediaproviderinternally.
- */
- publicstaticBitmapcreateImageThumbnail(StringfilePath,intkind){
- booleanwantMini=(kind==Images.Thumbnails.MINI_KIND);
- inttargetSize=wantMini
- ?TARGET_SIZE_MINI_THUMBNAIL
- :TARGET_SIZE_MICRO_THUMBNAIL;
- intmaxPixels=wantMini
- ?MAX_NUM_PIXELS_THUMBNAIL
- :MAX_NUM_PIXELS_MICRO_THUMBNAIL;
- SizedThumbnailBitmapsizedThumbnailBitmap=newSizedThumbnailBitmap();
- Bitmapbitmap=null;
- MediaFileTypefileType=MediaFile.getFileType(filePath);
- if(fileType!=null&&fileType.fileType==MediaFile.FILE_TYPE_JPEG){
- createThumbnailFromEXIF(filePath,targetSize,maxPixels,sizedThumbnailBitmap);
- bitmap=sizedThumbnailBitmap.mBitmap;
- }
- if(bitmap==null){
- try{
- FileDescriptorfd=newFileInputStream(filePath).getFD();
- BitmapFactory.Optionsoptions=newBitmapFactory.Options();
- options.inSampleSize=1;
- options.inJustDecodeBounds=true;
- BitmapFactory.decodeFileDescriptor(fd,null,options);
- if(options.mCancel||options.outWidth==-1
- ||options.outHeight==-1){
- returnnull;
- }
- options.inSampleSize=computeSampleSize(
- options,targetSize,maxPixels);
- options.inJustDecodeBounds=false;
- options.inDither=false;
- options.inPreferredConfig=Bitmap.Config.ARGB_8888;
- bitmap=BitmapFactory.decodeFileDescriptor(fd,null,options);
- }catch(IOExceptionex){
- Log.e(TAG,"",ex);
- }
- }
- if(kind==Images.Thumbnails.MICRO_KIND){
- //nowwemakeita"squarethumbnail"forMICRO_KINDthumbnail
- bitmap=extractThumbnail(bitmap,
- TARGET_SIZE_MICRO_THUMBNAIL,
- TARGET_SIZE_MICRO_THUMBNAIL,OPTIONS_RECYCLE_INPUT);
- }
- returnbitmap;
- }
- /**
- *Createavideothumbnailforavideo.Mayreturnnullifthevideois
- *corruptortheformatisnotsupported.
- *
- *@paramfilePaththepathofvideofile
- *@paramkindcouldbeMINI_KINDorMICRO_KIND
- */
- publicstaticBitmapcreateVideoThumbnail(StringfilePath,intkind){
- Bitmapbitmap=null;
- MediaMetadataRetrieverretriever=newMediaMetadataRetriever();
- try{
- retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
- retriever.setDataSource(filePath);
- bitmap=retriever.captureFrame();
- }catch(IllegalArgumentExceptionex){
- //Assumethisisacorruptvideofile
- }catch(RuntimeExceptionex){
- //Assumethisisacorruptvideofile.
- }finally{
- try{
- retriever.release();
- }catch(RuntimeExceptionex){
- //Ignorefailureswhilecleaningup.
- }
- }
- if(kind==Images.Thumbnails.MICRO_KIND&&bitmap!=null){
- bitmap=extractThumbnail(bitmap,
- TARGET_SIZE_MICRO_THUMBNAIL,
- TARGET_SIZE_MICRO_THUMBNAIL,
- OPTIONS_RECYCLE_INPUT);
- }
- returnbitmap;
- }
- /**
- *Createsacenteredbitmapofthedesiredsize.
- *
- *@paramsourceoriginalbitmapsource
- *@paramwidthtargetedwidth
- *@paramheighttargetedheight
- */
- publicstaticBitmapextractThumbnail(
- Bitmapsource,intwidth,intheight){
- returnextractThumbnail(source,width,height,OPTIONS_NONE);
- }
- /**
- *Createsacenteredbitmapofthedesiredsize.
- *
- *@paramsourceoriginalbitmapsource
- *@paramwidthtargetedwidth
- *@paramheighttargetedheight
- *@paramoptionsoptionsusedduringthumbnailextraction
- */
- publicstaticBitmapextractThumbnail(
- Bitmapsource,intwidth,intheight,intoptions){
- if(source==null){
- returnnull;
- }
- floatscale;
- if(source.getWidth()<source.getHeight()){
- scale=width/(float)source.getWidth();
- }else{
- scale=height/(float)source.getHeight();
- }
- Matrixmatrix=newMatrix();
- matrix.setScale(scale,scale);
- Bitmapthumbnail=transform(matrix,source,width,height,
- OPTIONS_SCALE_UP|options);
- returnthumbnail;
- }
- /*
- *ComputethesamplesizeasafunctionofminSideLength
- *andmaxNumOfPixels.
- *minSideLengthisusedtospecifythatminimalwidthorheightofa
- *bitmap.
- *maxNumOfPixelsisusedtospecifythemaximalsizeinpixelsthatis
- *tolerableintermsofmemoryusage.
- *
- *Thefunctionreturnsasamplesizebasedontheconstraints.
- *BothsizeandminSideLengthcanbepassedinasIImage.UNCONSTRAINED,
- *whichindicatesnocareofthecorrespondingconstraint.
- *Thefunctionsprefersreturningasamplesizethat
- *generatesasmallerbitmap,unlessminSideLength=IImage.UNCONSTRAINED.
- *
- *Also,thefunctionroundsupthesamplesizetoapowerof2ormultiple
- *of8becauseBitmapFactoryonlyhonorssamplesizethisway.
- *Forexample,BitmapFactorydownsamplesanimageby2eventhoughthe
- *requestis3.SoweroundupthesamplesizetoavoidOOM.
- */
- privatestaticintcomputeSampleSize(BitmapFactory.Optionsoptions,
- intminSideLength,intmaxNumOfPixels){
- intinitialSize=computeInitialSampleSize(options,minSideLength,
- maxNumOfPixels);
- introundedSize;
- if(initialSize<=8){
- roundedSize=1;
- while(roundedSize<initialSize){
- roundedSize<<=1;
- }
- }else{
- roundedSize=(initialSize+7)/8*8;
- }
- returnroundedSize;
- }
- privatestaticintcomputeInitialSampleSize(BitmapFactory.Optionsoptions,
- intminSideLength,intmaxNumOfPixels){
- doublew=options.outWidth;
- doubleh=options.outHeight;
- intlowerBound=(maxNumOfPixels==UNCONSTRAINED)?1:
- (int)Math.ceil(Math.sqrt(w*h/maxNumOfPixels));
- intupperBound=(minSideLength==UNCONSTRAINED)?128:
- (int)Math.min(Math.floor(w/minSideLength),
- Math.floor(h/minSideLength));
- if(upperBound<lowerBound){
- //returnthelargeronewhenthereisnooverlappingzone.
- returnlowerBound;
- }
- if((maxNumOfPixels==UNCONSTRAINED)&&
- (minSideLength==UNCONSTRAINED)){
- return1;
- }elseif(minSideLength==UNCONSTRAINED){
- returnlowerBound;
- }else{
- returnupperBound;
- }
- }
- /**
- *MakeabitmapfromagivenUri,minimalsidelength,andmaximumnumberofpixels.
- *Theimagedatawillbereadfromspecifiedpfdifit'snotnull,otherwise
- *anewinputstreamwillbecreatedusingspecifiedContentResolver.
- *
- *ClientsareallowedtopasstheirownBitmapFactory.Optionsusedforbitmapdecoding.A
- *newBitmapFactory.Optionswillbecreatedifoptionsisnull.
- */
- privatestaticBitmapmakeBitmap(intminSideLength,intmaxNumOfPixels,
- Uriuri,ContentResolvercr,ParcelFileDescriptorpfd,
- BitmapFactory.Optionsoptions){
- Bitmapb=null;
- try{
- if(pfd==null)pfd=makeInputStream(uri,cr);
- if(pfd==null)returnnull;
- if(options==null)options=newBitmapFactory.Options();
- FileDescriptorfd=pfd.getFileDescriptor();
- options.inSampleSize=1;
- options.inJustDecodeBounds=true;
- BitmapFactory.decodeFileDescriptor(fd,null,options);
- if(options.mCancel||options.outWidth==-1
- ||options.outHeight==-1){
- returnnull;
- }
- options.inSampleSize=computeSampleSize(
- options,minSideLength,maxNumOfPixels);
- options.inJustDecodeBounds=false;
- options.inDither=false;
- options.inPreferredConfig=Bitmap.Config.ARGB_8888;
- b=BitmapFactory.decodeFileDescriptor(fd,null,options);
- }catch(OutOfMemoryErrorex){
- Log.e(TAG,"Gotoomexception",ex);
- returnnull;
- }finally{
- closeSilently(pfd);
- }
- returnb;
- }
- privatestaticvoidcloseSilently(ParcelFileDescriptorc){
- if(c==null)return;
- try{
- c.close();
- }catch(Throwablet){
- //donothing
- }
- }
- privatestaticParcelFileDescriptormakeInputStream(
- Uriuri,ContentResolvercr){
- try{
- returncr.openFileDescriptor(uri,"r");
- }catch(IOExceptionex){
- returnnull;
- }
- }
- /**
- *TransformsourceBitmaptotargetedwidthandheight.
- */
- privatestaticBitmaptransform(Matrixscaler,
- Bitmapsource,
- inttargetWidth,
- inttargetHeight,
- intoptions){
- booleanscaleUp=(options&OPTIONS_SCALE_UP)!=0;
- booleanrecycle=(options&OPTIONS_RECYCLE_INPUT)!=0;
- intdeltaX=source.getWidth()-targetWidth;
- intdeltaY=source.getHeight()-targetHeight;
- if(!scaleUp&&(deltaX<0||deltaY<0)){
- /*
- *Inthiscasethebitmapissmaller,atleastinonedimension,
- *thanthetarget.Transformitbyplacingasmuchoftheimage
- *aspossibleintothetargetandleavingthetop/bottomor
- *left/right(orboth)black.
- */
- Bitmapb2=Bitmap.createBitmap(targetWidth,targetHeight,
- Bitmap.Config.ARGB_8888);
- Canvasc=newCanvas(b2);
- intdeltaXHalf=Math.max(0,deltaX/2);
- intdeltaYHalf=Math.max(0,deltaY/2);
- Rectsrc=newRect(
- deltaXHalf,
- deltaYHalf,
- deltaXHalf+Math.min(targetWidth,source.getWidth()),
- deltaYHalf+Math.min(targetHeight,source.getHeight()));
- intdstX=(targetWidth-src.width())/2;
- intdstY=(targetHeight-src.height())/2;
- Rectdst=newRect(
- dstX,
- dstY,
- targetWidth-dstX,
- targetHeight-dstY);
- c.drawBitmap(source,src,dst,null);
- if(recycle){
- source.recycle();
- }
- returnb2;
- }
- floatbitmapWidthF=source.getWidth();
- floatbitmapHeightF=source.getHeight();
- floatbitmapAspect=bitmapWidthF/bitmapHeightF;
- floatviewAspect=(float)targetWidth/targetHeight;
- if(bitmapAspect>viewAspect){
- floatscale=targetHeight/bitmapHeightF;
- if(scale<.9F||scale>1F){
- scaler.setScale(scale,scale);
- }else{
- scaler=null;
- }
- }else{
- floatscale=targetWidth/bitmapWidthF;
- if(scale<.9F||scale>1F){
- scaler.setScale(scale,scale);
- }else{
- scaler=null;
- }
- }
- Bitmapb1;
- if(scaler!=null){
- //thisisusedforminithumbandcrop,sowewanttofilterhere.
- b1=Bitmap.createBitmap(source,0,0,
- source.getWidth(),source.getHeight(),scaler,true);
- }else{
- b1=source;
- }
- if(recycle&&b1!=source){
- source.recycle();
- }
- intdx1=Math.max(0,b1.getWidth()-targetWidth);
- intdy1=Math.max(0,b1.getHeight()-targetHeight);
- Bitmapb2=Bitmap.createBitmap(
- b1,
- dx1/2,
- dy1/2,
- targetWidth,
- targetHeight);
- if(b2!=b1){
- if(recycle||b1!=source){
- b1.recycle();
- }
- }
- returnb2;
- }
- /**
- *SizedThumbnailBitmapcontainsthebitmap,whichisdownsampledeitherfrom
- *thethumbnailinexiforthefullimage.
- *mThumbnailData,mThumbnailWidthandmThumbnailHeightaresettogetheronlyifmThumbnail
- *isnotnull.
- *
- *Thewidth/heightofthesizedbitmapmaybedifferentfrommThumbnailWidth/mThumbnailHeight.
- */
- privatestaticclassSizedThumbnailBitmap{
- publicbyte[]mThumbnailData;
- publicBitmapmBitmap;
- publicintmThumbnailWidth;
- publicintmThumbnailHeight;
- }
- /**
- *CreatesabitmapbyeitherdownsamplingfromthethumbnailinEXIForthefullimage.
- *ThefunctionsreturnsaSizedThumbnailBitmap,
- *whichcontainsadownsampledbitmapandthethumbnaildatainEXIFifexists.
- */
- privatestaticvoidcreateThumbnailFromEXIF(StringfilePath,inttargetSize,
- intmaxPixels,SizedThumbnailBitmapsizedThumbBitmap){
- if(filePath==null)return;
- ExifInterfaceexif=null;
- byte[]thumbData=null;
- try{
- exif=newExifInterface(filePath);
- if(exif!=null){
- thumbData=exif.getThumbnail();
- }
- }catch(IOExceptionex){
- Log.w(TAG,ex);
- }
- BitmapFactory.OptionsfullOptions=newBitmapFactory.Options();
- BitmapFactory.OptionsexifOptions=newBitmapFactory.Options();
- intexifThumbWidth=0;
- intfullThumbWidth=0;
- //ComputeexifThumbWidth.
- if(thumbData!=null){
- exifOptions.inJustDecodeBounds=true;
- BitmapFactory.decodeByteArray(thumbData,0,thumbData.length,exifOptions);
- exifOptions.inSampleSize=computeSampleSize(exifOptions,targetSize,maxPixels);
- exifThumbWidth=exifOptions.outWidth/exifOptions.inSampleSize;
- }
- //ComputefullThumbWidth.
- fullOptions.inJustDecodeBounds=true;
- BitmapFactory.decodeFile(filePath,fullOptions);
- fullOptions.inSampleSize=computeSampleSize(fullOptions,targetSize,maxPixels);
- fullThumbWidth=fullOptions.outWidth/fullOptions.inSampleSize;
- //ChoosethelargerthumbnailasthereturningsizedThumbBitmap.
- if(thumbData!=null&&exifThumbWidth>=fullThumbWidth){
- intwidth=exifOptions.outWidth;
- intheight=exifOptions.outHeight;
- exifOptions.inJustDecodeBounds=false;
- sizedThumbBitmap.mBitmap=BitmapFactory.decodeByteArray(thumbData,0,
- thumbData.length,exifOptions);
- if(sizedThumbBitmap.mBitmap!=null){
- sizedThumbBitmap.mThumbnailData=thumbData;
- sizedThumbBitmap.mThumbnailWidth=width;
- sizedThumbBitmap.mThumbnailHeight=height;
- }
- }else{
- fullOptions.inJustDecodeBounds=false;
- sizedThumbBitmap.mBitmap=BitmapFactory.decodeFile(filePath,fullOptions);
- }
- }
- }
更多相关文章
- Android中快速为Recyclerview添加头部
- Android(安卓)图片加载笔记
- mysql错误:Access denied for user 'root'@'172.19.100.123' to d
- Android事件总线框架设计:EventBus3.0源码详解与架构分析(中)
- android 判断手机是否是国内的手机的方法
- Android(安卓)ViewPager切换的N种动画
- Android(安卓)touch事件的派发流程
- android kotlin 学习笔记基础篇(一)
- 下载最新android adt的方法