Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android--生成縮略圖------方法總結

Android--生成縮略圖------方法總結

編輯:關於Android編程

在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來縮放。

首先要獲得原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等經過人家一陣加工而成。
效率好像比第二種方法高一點點。

下面是我的例子:

 

[html]view plaincopy  
  1.  
  2. android:layout_width="fill_parent"
  3. android:layout_height="fill_parent"
  4. >
  5.  
  6. android:id="@+id/imageShow"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. />
  10. android:id="@+id/image2"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. />
  14. android:id="@+id/text"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:text="@string/hello"
  18. />

  19. [java]view plaincopy  
    1. packagecom.linc.ResolvePicture;
    2.  
    3. importjava.io.File;
    4. importjava.io.FileNotFoundException;
    5. importjava.io.FileOutputStream;
    6. importjava.io.IOException;
    7.  
    8. importandroid.app.Activity;
    9. importandroid.graphics.Bitmap;
    10. importandroid.graphics.BitmapFactory;
    11. importandroid.graphics.Matrix;
    12. importandroid.graphics.drawable.BitmapDrawable;
    13. importandroid.graphics.drawable.Drawable;
    14. importandroid.media.ThumbnailUtils;
    15. importandroid.os.Bundle;
    16. importandroid.util.Log;
    17. importandroid.widget.ImageView;
    18. importandroid.widget.TextView;
    19.  
    20. publicclassResolvePictureextendsActivity{
    21. privatestaticStringtag="ResolvePicture";
    22. DrawablebmImg;
    23. ImageViewimView;
    24. ImageViewimView2;
    25. TextViewtext;
    26. StringtheTime;
    27. longstart,stop;
    28. /**Calledwhentheactivityisfirstcreated.*/
    29. @Override
    30. publicvoidonCreate(BundlesavedInstanceState){
    31. super.onCreate(savedInstanceState);
    32. setContentView(R.layout.main);
    33.  
    34. text=(TextView)findViewById(R.id.text);
    35.  
    36. imView=(ImageView)findViewById(R.id.imageShow);
    37. imView2=(ImageView)findViewById(R.id.image2);
    38.  
    39. Bitmapbitmap=BitmapFactory.decodeResource(getResources(),
    40. R.drawable.pic);
    41.  
    42. start=System.currentTimeMillis();
    43.  
    44. //imView.setImageDrawable(resizeImage(bitmap,300,100));
    45.  
    46. imView2.setImageDrawable(resizeImage2("/sdcard/2.jpeg",200,100));
    47.  
    48. stop=System.currentTimeMillis();
    49.  
    50. StringtheTime=String.format("\n1iterative:(%dmsec)",
    51. stop-start);
    52.  
    53. start=System.currentTimeMillis();
    54. imView.setImageBitmap(ThumbnailUtils.extractThumbnail(bitmap,200,100));//2.2才加進來的新類,簡單易用
    55. //imView.setImageDrawable(resizeImage(bitmap,30,30));
    56. stop=System.currentTimeMillis();
    57.  
    58. theTime+=String.format("\n2iterative:(%dmsec)",
    59. stop-start);
    60.  
    61. text.setText(theTime);
    62. }
    63.  
    64. //使用Bitmap加Matrix來縮放
    65. publicstaticDrawableresizeImage(Bitmapbitmap,intw,inth)
    66. {
    67. BitmapBitmapOrg=bitmap;
    68. intwidth=BitmapOrg.getWidth();
    69. intheight=BitmapOrg.getHeight();
    70. intnewWidth=w;
    71. intnewHeight=h;
    72.  
    73. floatscaleWidth=((float)newWidth)/width;
    74. floatscaleHeight=((float)newHeight)/height;
    75.  
    76. Matrixmatrix=newMatrix();
    77. matrix.postScale(scaleWidth,scaleHeight);
    78. //ifyouwanttorotatetheBitmap
    79. //matrix.postRotate(45);
    80. BitmapresizedBitmap=Bitmap.createBitmap(BitmapOrg,0,0,width,
    81. height,matrix,true);
    82. returnnewBitmapDrawable(resizedBitmap);
    83. }
    84.  
    85. //使用BitmapFactory.Options的inSampleSize參數來縮放
    86. publicstaticDrawableresizeImage2(Stringpath,
    87. intwidth,intheight)
    88. {
    89. BitmapFactory.Optionsoptions=newBitmapFactory.Options();
    90. options.inJustDecodeBounds=true;//不加載bitmap到內存中
    91. BitmapFactory.decodeFile(path,options);
    92. intoutWidth=options.outWidth;
    93. intoutHeight=options.outHeight;
    94. options.inDither=false;
    95. options.inPreferredConfig=Bitmap.Config.ARGB_8888;
    96. options.inSampleSize=1;
    97.  
    98. if(outWidth!=0&&outHeight!=0&&width!=0&&height!=0)
    99. {
    100. intsampleSize=(outWidth/width+outHeight/height)/2;
    101. Log.d(tag,"sampleSize="+sampleSize);
    102. options.inSampleSize=sampleSize;
    103. }
    104.  
    105. options.inJustDecodeBounds=false;
    106. returnnewBitmapDrawable(BitmapFactory.decodeFile(path,options));
    107. }
    108.  
    109. //圖片保存
    110. privatevoidsaveThePicture(Bitmapbitmap)
    111. {
    112. Filefile=newFile("/sdcard/2.jpeg");
    113. try
    114. {
    115. FileOutputStreamfos=newFileOutputStream(file);
    116. if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos))
    117. {
    118. fos.flush();
    119. fos.close();
    120. }
    121. }
    122. catch(FileNotFoundExceptione1)
    123. {
    124. e1.printStackTrace();
    125. }
    126. catch(IOExceptione2)
    127. {
    128. e2.printStackTrace();
    129. }
    130. }
    131. }

ThumbnailUtils源碼:
[java]view plaincopy
  1. /*
  2. *Copyright(C)2009TheAndroidOpenSourceProject
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16.  
  17. packageandroid.media;
  18.  
  19. importandroid.content.ContentResolver;
  20. importandroid.content.ContentUris;
  21. importandroid.content.ContentValues;
  22. importandroid.database.Cursor;
  23. importandroid.graphics.Bitmap;
  24. importandroid.graphics.BitmapFactory;
  25. importandroid.graphics.Canvas;
  26. importandroid.graphics.Matrix;
  27. importandroid.graphics.Rect;
  28. importandroid.media.MediaMetadataRetriever;
  29. importandroid.media.MediaFile.MediaFileType;
  30. importandroid.net.Uri;
  31. importandroid.os.ParcelFileDescriptor;
  32. importandroid.provider.BaseColumns;
  33. importandroid.provider.MediaStore.Images;
  34. importandroid.provider.MediaStore.Images.Thumbnails;
  35. importandroid.util.Log;
  36.  
  37. importjava.io.FileInputStream;
  38. importjava.io.FileDescriptor;
  39. importjava.io.IOException;
  40. importjava.io.OutputStream;
  41.  
  42. /**
  43. *Thumbnailgenerationroutinesformediaprovider.
  44. */
  45.  
  46. publicclassThumbnailUtils{
  47. privatestaticfinalStringTAG="ThumbnailUtils";
  48.  
  49. /*Maximumpixelssizeforcreatedbitmap.*/
  50. privatestaticfinalintMAX_NUM_PIXELS_THUMBNAIL=512*384;
  51. privatestaticfinalintMAX_NUM_PIXELS_MICRO_THUMBNAIL=128*128;
  52. privatestaticfinalintUNCONSTRAINED=-1;
  53.  
  54. /*Optionsusedinternally.*/
  55. privatestaticfinalintOPTIONS_NONE=0x0;
  56. privatestaticfinalintOPTIONS_SCALE_UP=0x1;
  57.  
  58. /**
  59. *Constantusedtoindicateweshouldrecycletheinputin
  60. *{@link#extractThumbnail(Bitmap,int,int,int)}unlesstheoutputistheinput.
  61. */
  62. publicstaticfinalintOPTIONS_RECYCLE_INPUT=0x2;
  63.  
  64. /**
  65. *Constantusedtoindicatethedimensionofminithumbnail.
  66. *@hideOnlyusedbymediaframeworkandmediaproviderinternally.
  67. */
  68. publicstaticfinalintTARGET_SIZE_MINI_THUMBNAIL=320;
  69.  
  70. /**
  71. *Constantusedtoindicatethedimensionofmicrothumbnail.
  72. *@hideOnlyusedbymediaframeworkandmediaproviderinternally.
  73. */
  74. publicstaticfinalintTARGET_SIZE_MICRO_THUMBNAIL=96;
  75.  
  76. /**
  77. *ThismethodfirstexaminesifthethumbnailembeddedinEXIFisbiggerthanourtarget
  78. *size.Ifnot,thenit'llcreateathumbnailfromoriginalimage.Duetoefficiency
  79. *consideration,wewanttoletMediaThumbRequestavoidcallingthismethodtwicefor
  80. *bothkinds,soitonlyrequestsforMICRO_KINDandsetsaveImagetotrue.
  81. *
  82. *Thismethodalwaysreturnsa"squarethumbnail"forMICRO_KINDthumbnail.
  83. *
  84. *@paramfilePaththepathofimagefile
  85. *@paramkindcouldbeMINI_KINDorMICRO_KIND
  86. *@returnBitmap
  87. *
  88. *@hideThismethodisonlyusedbymediaframeworkandmediaproviderinternally.
  89. */
  90. publicstaticBitmapcreateImageThumbnail(StringfilePath,intkind){
  91. booleanwantMini=(kind==Images.Thumbnails.MINI_KIND);
  92. inttargetSize=wantMini
  93. ?TARGET_SIZE_MINI_THUMBNAIL
  94. :TARGET_SIZE_MICRO_THUMBNAIL;
  95. intmaxPixels=wantMini
  96. ?MAX_NUM_PIXELS_THUMBNAIL
  97. :MAX_NUM_PIXELS_MICRO_THUMBNAIL;
  98. SizedThumbnailBitmapsizedThumbnailBitmap=newSizedThumbnailBitmap();
  99. Bitmapbitmap=null;
  100. MediaFileTypefileType=MediaFile.getFileType(filePath);
  101. if(fileType!=null&&fileType.fileType==MediaFile.FILE_TYPE_JPEG){
  102. createThumbnailFromEXIF(filePath,targetSize,maxPixels,sizedThumbnailBitmap);
  103. bitmap=sizedThumbnailBitmap.mBitmap;
  104. }
  105.  
  106. if(bitmap==null){
  107. try{
  108. FileDescriptorfd=newFileInputStream(filePath).getFD();
  109. BitmapFactory.Optionsoptions=newBitmapFactory.Options();
  110. options.inSampleSize=1;
  111. options.inJustDecodeBounds=true;
  112. BitmapFactory.decodeFileDescriptor(fd,null,options);
  113. if(options.mCancel||options.outWidth==-1
  114. ||options.outHeight==-1){
  115. returnnull;
  116. }
  117. options.inSampleSize=computeSampleSize(
  118. options,targetSize,maxPixels);
  119. options.inJustDecodeBounds=false;
  120.  
  121. options.inDither=false;
  122. options.inPreferredConfig=Bitmap.Config.ARGB_8888;
  123. bitmap=BitmapFactory.decodeFileDescriptor(fd,null,options);
  124. }catch(IOExceptionex){
  125. Log.e(TAG,"",ex);
  126. }
  127. }
  128.  
  129. if(kind==Images.Thumbnails.MICRO_KIND){
  130. //nowwemakeita"squarethumbnail"forMICRO_KINDthumbnail
  131. bitmap=extractThumbnail(bitmap,
  132. TARGET_SIZE_MICRO_THUMBNAIL,
  133. TARGET_SIZE_MICRO_THUMBNAIL,OPTIONS_RECYCLE_INPUT);
  134. }
  135. returnbitmap;
  136. }
  137.  
  138. /**
  139. *Createavideothumbnailforavideo.Mayreturnnullifthevideois
  140. *corruptortheformatisnotsupported.
  141. *
  142. *@paramfilePaththepathofvideofile
  143. *@paramkindcouldbeMINI_KINDorMICRO_KIND
  144. */
  145. publicstaticBitmapcreateVideoThumbnail(StringfilePath,intkind){
  146. Bitmapbitmap=null;
  147. MediaMetadataRetrieverretriever=newMediaMetadataRetriever();
  148. try{
  149. retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
  150. retriever.setDataSource(filePath);
  151. bitmap=retriever.captureFrame();
  152. }catch(IllegalArgumentExceptionex){
  153. //Assumethisisacorruptvideofile
  154. }catch(RuntimeExceptionex){
  155. //Assumethisisacorruptvideofile.
  156. }finally{
  157. try{
  158. retriever.release();
  159. }catch(RuntimeExceptionex){
  160. //Ignorefailureswhilecleaningup.
  161. }
  162. }
  163. if(kind==Images.Thumbnails.MICRO_KIND&&bitmap!=null){
  164. bitmap=extractThumbnail(bitmap,
  165. TARGET_SIZE_MICRO_THUMBNAIL,
  166. TARGET_SIZE_MICRO_THUMBNAIL,
  167. OPTIONS_RECYCLE_INPUT);
  168. }
  169. returnbitmap;
  170. }
  171.  
  172. /**
  173. *Createsacenteredbitmapofthedesiredsize.
  174. *
  175. *@paramsourceoriginalbitmapsource
  176. *@paramwidthtargetedwidth
  177. *@paramheighttargetedheight
  178. */
  179. publicstaticBitmapextractThumbnail(
  180. Bitmapsource,intwidth,intheight){
  181. returnextractThumbnail(source,width,height,OPTIONS_NONE);
  182. }
  183.  
  184. /**
  185. *Createsacenteredbitmapofthedesiredsize.
  186. *
  187. *@paramsourceoriginalbitmapsource
  188. *@paramwidthtargetedwidth
  189. *@paramheighttargetedheight
  190. *@paramoptionsoptionsusedduringthumbnailextraction
  191. */
  192. publicstaticBitmapextractThumbnail(
  193. Bitmapsource,intwidth,intheight,intoptions){
  194. if(source==null){
  195. returnnull;
  196. }
  197.  
  198. floatscale;
  199. if(source.getWidth() scale=width/(float)source.getWidth();
  200. }else{
  201. scale=height/(float)source.getHeight();
  202. }
  203. Matrixmatrix=newMatrix();
  204. matrix.setScale(scale,scale);
  205. Bitmapthumbnail=transform(matrix,source,width,height,
  206. OPTIONS_SCALE_UP|options);
  207. returnthumbnail;
  208. }
  209.  
  210. /*
  211. *ComputethesamplesizeasafunctionofminSideLength
  212. *andmaxNumOfPixels.
  213. *minSideLengthisusedtospecifythatminimalwidthorheightofa
  214. *bitmap.
  215. *maxNumOfPixelsisusedtospecifythemaximalsizeinpixelsthatis
  216. *tolerableintermsofmemoryusage.
  217. *
  218. *Thefunctionreturnsasamplesizebasedontheconstraints.
  219. *BothsizeandminSideLengthcanbepassedinasIImage.UNCONSTRAINED,
  220. *whichindicatesnocareofthecorrespondingconstraint.
  221. *Thefunctionsprefersreturningasamplesizethat
  222. *generatesasmallerbitmap,unlessminSideLength=IImage.UNCONSTRAINED.
  223. *
  224. *Also,thefunctionroundsupthesamplesizetoapowerof2ormultiple
  225. *of8becauseBitmapFactoryonlyhonorssamplesizethisway.
  226. *Forexample,BitmapFactorydownsamplesanimageby2eventhoughthe
  227. *requestis3.SoweroundupthesamplesizetoavoidOOM.
  228. */
  229. privatestaticintcomputeSampleSize(BitmapFactory.Optionsoptions,
  230. intminSideLength,intmaxNumOfPixels){
  231. intinitialSize=computeInitialSampleSize(options,minSideLength,
  232. maxNumOfPixels);
  233.  
  234. introundedSize;
  235. if(initialSize<=8){
  236. roundedSize=1;
  237. while(roundedSize roundedSize<<=1;
  238. }
  239. }else{
  240. roundedSize=(initialSize+7)/8*8;
  241. }
  242.  
  243. returnroundedSize;
  244. }
  245.  
  246. privatestaticintcomputeInitialSampleSize(BitmapFactory.Optionsoptions,
  247. intminSideLength,intmaxNumOfPixels){
  248. doublew=options.outWidth;
  249. doubleh=options.outHeight;
  250.  
  251. intlowerBound=(maxNumOfPixels==UNCONSTRAINED)?1:
  252. (int)Math.ceil(Math.sqrt(w*h/maxNumOfPixels));
  253. intupperBound=(minSideLength==UNCONSTRAINED)?128:
  254. (int)Math.min(Math.floor(w/minSideLength),
  255. Math.floor(h/minSideLength));
  256.  
  257. if(upperBound //returnthelargeronewhenthereisnooverlappingzone.
  258. returnlowerBound;
  259. }
  260.  
  261. if((maxNumOfPixels==UNCONSTRAINED)&&
  262. (minSideLength==UNCONSTRAINED)){
  263. return1;
  264. }elseif(minSideLength==UNCONSTRAINED){
  265. returnlowerBound;
  266. }else{
  267. returnupperBound;
  268. }
  269. }
  270.  
  271. /**
  272. *MakeabitmapfromagivenUri,minimalsidelength,andmaximumnumberofpixels.
  273. *Theimagedatawillbereadfromspecifiedpfdifit'snotnull,otherwise
  274. *anewinputstreamwillbecreatedusingspecifiedContentResolver.
  275. *
  276. *ClientsareallowedtopasstheirownBitmapFactory.Optionsusedforbitmapdecoding.A
  277. *newBitmapFactory.Optionswillbecreatedifoptionsisnull.
  278. */
  279. privatestaticBitmapmakeBitmap(intminSideLength,intmaxNumOfPixels,
  280. Uriuri,ContentResolvercr,ParcelFileDescriptorpfd,
  281. BitmapFactory.Optionsoptions){
  282. Bitmapb=null;
  283. try{
  284. if(pfd==null)pfd=makeInputStream(uri,cr);
  285. if(pfd==null)returnnull;
  286. if(options==null)options=newBitmapFactory.Options();
  287.  
  288. FileDescriptorfd=pfd.getFileDescriptor();
  289. options.inSampleSize=1;
  290. options.inJustDecodeBounds=true;
  291. BitmapFactory.decodeFileDescriptor(fd,null,options);
  292. if(options.mCancel||options.outWidth==-1
  293. ||options.outHeight==-1){
  294. returnnull;
  295. }
  296. options.inSampleSize=computeSampleSize(
  297. options,minSideLength,maxNumOfPixels);
  298. options.inJustDecodeBounds=false;
  299.  
  300. options.inDither=false;
  301. options.inPreferredConfig=Bitmap.Config.ARGB_8888;
  302. b=BitmapFactory.decodeFileDescriptor(fd,null,options);
  303. }catch(OutOfMemoryErrorex){
  304. Log.e(TAG,"Gotoomexception",ex);
  305. returnnull;
  306. }finally{
  307. closeSilently(pfd);
  308. }
  309. returnb;
  310. }
  311.  
  312. privatestaticvoidcloseSilently(ParcelFileDescriptorc){
  313. if(c==null)return;
  314. try{
  315. c.close();
  316. }catch(Throwablet){
  317. //donothing
  318. }
  319. }
  320.  
  321. privatestaticParcelFileDescriptormakeInputStream(
  322. Uriuri,ContentResolvercr){
  323. try{
  324. returncr.openFileDescriptor(uri,"r");
  325. }catch(IOExceptionex){
  326. returnnull;
  327. }
  328. }
  329.  
  330. /**
  331. *TransformsourceBitmaptotargetedwidthandheight.
  332. */
  333. privatestaticBitmaptransform(Matrixscaler,
  334. Bitmapsource,
  335. inttargetWidth,
  336. inttargetHeight,
  337. intoptions){
  338. booleanscaleUp=(options&OPTIONS_SCALE_UP)!=0;
  339. booleanrecycle=(options&OPTIONS_RECYCLE_INPUT)!=0;
  340.  
  341. intdeltaX=source.getWidth()-targetWidth;
  342. intdeltaY=source.getHeight()-targetHeight;
  343. if(!scaleUp&&(deltaX<0||deltaY<0)){
  344. /*
  345. *Inthiscasethebitmapissmaller,atleastinonedimension,
  346. *thanthetarget.Transformitbyplacingasmuchoftheimage
  347. *aspossibleintothetargetandleavingthetop/bottomor
  348. *left/right(orboth)black.
  349. */
  350. Bitmapb2=Bitmap.createBitmap(targetWidth,targetHeight,
  351. Bitmap.Config.ARGB_8888);
  352. Canvasc=newCanvas(b2);
  353.  
  354. intdeltaXHalf=Math.max(0,deltaX/2);
  355. intdeltaYHalf=Math.max(0,deltaY/2);
  356. Rectsrc=newRect(
  357. deltaXHalf,
  358. deltaYHalf,
  359. deltaXHalf+Math.min(targetWidth,source.getWidth()),
  360. deltaYHalf+Math.min(targetHeight,source.getHeight()));
  361. intdstX=(targetWidth-src.width())/2;
  362. intdstY=(targetHeight-src.height())/2;
  363. Rectdst=newRect(
  364. dstX,
  365. dstY,
  366. targetWidth-dstX,
  367. targetHeight-dstY);
  368. c.drawBitmap(source,src,dst,null);
  369. if(recycle){
  370. source.recycle();
  371. }
  372. returnb2;
  373. }
  374. floatbitmapWidthF=source.getWidth();
  375. floatbitmapHeightF=source.getHeight();
  376.  
  377. floatbitmapAspect=bitmapWidthF/bitmapHeightF;
  378. floatviewAspect=(float)targetWidth/targetHeight;
  379.  
  380. if(bitmapAspect>viewAspect){
  381. floatscale=targetHeight/bitmapHeightF;
  382. if(scale<.9F||scale>1F){
  383. scaler.setScale(scale,scale);
  384. }else{
  385. scaler=null;
  386. }
  387. }else{
  388. floatscale=targetWidth/bitmapWidthF;
  389. if(scale<.9F||scale>1F){
  390. scaler.setScale(scale,scale);
  391. }else{
  392. scaler=null;
  393. }
  394. }
  395.  
  396. Bitmapb1;
  397. if(scaler!=null){
  398. //thisisusedforminithumbandcrop,sowewanttofilterhere.
  399. b1=Bitmap.createBitmap(source,0,0,
  400. source.getWidth(),source.getHeight(),scaler,true);
  401. }else{
  402. b1=source;
  403. }
  404.  
  405. if(recycle&&b1!=source){
  406. source.recycle();
  407. }
  408.  
  409. intdx1=Math.max(0,b1.getWidth()-targetWidth);
  410. intdy1=Math.max(0,b1.getHeight()-targetHeight);
  411.  
  412. Bitmapb2=Bitmap.createBitmap(
  413. b1,
  414. dx1/2,
  415. dy1/2,
  416. targetWidth,
  417. targetHeight);
  418.  
  419. if(b2!=b1){
  420. if(recycle||b1!=source){
  421. b1.recycle();
  422. }
  423. }
  424.  
  425. returnb2;
  426. }
  427.  
  428. /**
  429. *SizedThumbnailBitmapcontainsthebitmap,whichisdownsampledeitherfrom
  430. *thethumbnailinexiforthefullimage.
  431. *mThumbnailData,mThumbnailWidthandmThumbnailHeightaresettogetheronlyifmThumbnail
  432. *isnotnull.
  433. *
  434. *Thewidth/heightofthesizedbitmapmaybedifferentfrommThumbnailWidth/mThumbnailHeight.
  435. */
  436. privatestaticclassSizedThumbnailBitmap{
  437. publicbyte[]mThumbnailData;
  438. publicBitmapmBitmap;
  439. publicintmThumbnailWidth;
  440. publicintmThumbnailHeight;
  441. }
  442.  
  443. /**
  444. *CreatesabitmapbyeitherdownsamplingfromthethumbnailinEXIForthefullimage.
  445. *ThefunctionsreturnsaSizedThumbnailBitmap,
  446. *whichcontainsadownsampledbitmapandthethumbnaildatainEXIFifexists.
  447. */
  448. privatestaticvoidcreateThumbnailFromEXIF(StringfilePath,inttargetSize,
  449. intmaxPixels,SizedThumbnailBitmapsizedThumbBitmap){
  450. if(filePath==null)return;
  451.  
  452. ExifInterfaceexif=null;
  453. byte[]thumbData=null;
  454. try{
  455. exif=newExifInterface(filePath);
  456. if(exif!=null){
  457. thumbData=exif.getThumbnail();
  458. }
  459. }catch(IOExceptionex){
  460. Log.w(TAG,ex);
  461. }
  462.  
  463. BitmapFactory.OptionsfullOptions=newBitmapFactory.Options();
  464. BitmapFactory.OptionsexifOptions=newBitmapFactory.Options();
  465. intexifThumbWidth=0;
  466. intfullThumbWidth=0;
  467.  
  468. //ComputeexifThumbWidth.
  469. if(thumbData!=null){
  470. exifOptions.inJustDecodeBounds=true;
  471. BitmapFactory.decodeByteArray(thumbData,0,thumbData.length,exifOptions);
  472. exifOptions.inSampleSize=computeSampleSize(exifOptions,targetSize,maxPixels);
  473. exifThumbWidth=exifOptions.outWidth/exifOptions.inSampleSize;
  474. }
  475.  
  476. //ComputefullThumbWidth.
  477. fullOptions.inJustDecodeBounds=true;
  478. BitmapFactory.decodeFile(filePath,fullOptions);
  479. fullOptions.inSampleSize=computeSampleSize(fullOptions,targetSize,maxPixels);
  480. fullThumbWidth=fullOptions.outWidth/fullOptions.inSampleSize;
  481.  
  482. //ChoosethelargerthumbnailasthereturningsizedThumbBitmap.
  483. if(thumbData!=null&&exifThumbWidth>=fullThumbWidth){
  484. intwidth=exifOptions.outWidth;
  485. intheight=exifOptions.outHeight;
  486. exifOptions.inJustDecodeBounds=false;
  487. sizedThumbBitmap.mBitmap=BitmapFactory.decodeByteArray(thumbData,0,
  488. thumbData.length,exifOptions);
  489. if(sizedThumbBitmap.mBitmap!=null){
  490. sizedThumbBitmap.mThumbnailData=thumbData;
  491. sizedThumbBitmap.mThumbnailWidth=width;
  492. sizedThumbBitmap.mThumbnailHeight=height;
  493. }
  494. }else{
  495. fullOptions.inJustDecodeBounds=false;
  496. sizedThumbBitmap.mBitmap=BitmapFactory.decodeFile(filePath,fullOptions);
  497. }
  498. }
  499. }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved