在Android经常使用到Bitmap用于显示图片,如果图片过大,容易出现"OutOfMemory"异常,所以要对图片进行压缩显示。

通常使用BitmapFactory类的几个方法(decodeByteArray(), decodeFile(), decodeResource()等)来建立一个bitmap,在生成bitmap前,可以通过BitmapFactory.Options来设置属性,来保证不会出现OutOfMemory异常。首先可以通过需要显示图片的长宽来获取缩小的倍数:

privateintcalculateInSampleSize(BitmapFactory.Optionsoptions,intreqWidth,intreqHeight){//Rawheightandwidthofp_w_picpathfinalintheight=options.outHeight;finalintwidth=options.outWidth;intinSampleSize=1;if(height>reqHeight||width>reqWidth){if(width>height){inSampleSize=Math.round((float)height/(float)reqHeight);}else{inSampleSize=Math.round((float)width/(float)reqWidth);}}returninSampleSize;}

PS:官方文档说到,图片压缩时,使用2的倍数压缩效率会高,就是2,4,8…这种,我这里使用的是更接近需要的压缩倍数,官方文档看这里。

使用两种方式来压缩图片,一种是根据需要的图片长宽,一种是根据需要的图片大小(就是多少K)。

先看第一种:

publicBitmapGetThumbImageByWH(booleanisRound,StringimgPath,intp_w_picpathwidth,intp_w_picpathheight){try{Filepicture=newFile(imgPath);BitmapFactory.OptionsbitmapFactoryOptions=newBitmapFactory.Options();//setheightandwidthofp_w_picpathbitmapFactoryOptions.inJustDecodeBounds=true;Bitmapbmap=BitmapFactory.decodeFile(picture.getAbsolutePath(),bitmapFactoryOptions);intinSampleSize=calculateInSampleSize(bitmapFactoryOptions,p_w_picpathwidth,p_w_picpathheight);bitmapFactoryOptions.inSampleSize=inSampleSize;bitmapFactoryOptions.inJustDecodeBounds=false;bmap=BitmapFactory.decodeFile(picture.getAbsolutePath(),bitmapFactoryOptions);returnbmap;}catch(Exceptione){e.printStackTrace();returnnull;}}

PS:如果使用一个BitmapFactory.Options对象,要先把该对象的inJustDecodeBounds属性设置为true,inSampleSize设置完成后再设置为false。后面的是用来翻转图片的。

第二种方式:

publicBitmapgetThumbImageBySize(Stringimgpath,intsize,booleanadjustOrientation){Filefile=newFile(imgpath);FileInputStreamfis=null;intfilesize=0;try{fis=newFileInputStream(file);filesize=fis.available();Log.v("filelength",""+filesize);fis.close();}catch(Exceptionex){Log.v("Readfileerror",""+ex.getMessage());}if(filesize/1024<size){returnBitmapFactory.decodeFile(imgpath);}//Revision:BitmapFactory.Optionsoptions=newBitmapFactory.Options();//Setitfalsetonotbuildthebitmap,justrecorditswidthandheightoptions.inJustDecodeBounds=true;//GettheOptionsobjectbythepathBitmapFactory.decodeFile(imgpath,options);intheight=options.outHeight;intwidth=options.outWidth;BitmapsmallBitmap=null;doublemultiple=(float)(width*height*4)/(float)(size*1024);intinSampleSize=(int)Math.ceil(Math.sqrt(((float)filesize/1024.0)/(float)size));options.inSampleSize=inSampleSize;options.inJustDecodeBounds=false;smallBitmap=BitmapFactory.decodeFile(imgpath,options);returnsmallBitmap;}}