在Android经常使用到Bitmap用于显示图片,如果图片过大,容易出现"OutOfMemory"异常,所以要对图片进行压缩显示。
通常使用BitmapFactory类的几个方法(decodeByteArray(), decodeFile(), decodeResource()等)来建立一个bitmap,在生成bitmap前,可以通过BitmapFactory.Options来设置属性,来保证不会出现OutOfMemory异常。首先可以通过需要显示图片的长宽来获取缩小的倍数:
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; }
PS:官方文档说到,图片压缩时,使用2的倍数压缩效率会高,就是2,4,8…这种,我这里使用的是更接近需要的压缩倍数,官方文档看这里。
使用两种方式来压缩图片,一种是根据需要的图片长宽,一种是根据需要的图片大小(就是多少K)。
先看第一种:
public Bitmap GetThumbImageByWH(boolean isRound,String imgPath, int imagewidth, int imageheight) { try { File picture = new File(imgPath); BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options(); // set height and width of image bitmapFactoryOptions.inJustDecodeBounds = true; Bitmap bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); int inSampleSize = calculateInSampleSize(bitmapFactoryOptions,imagewidth,imageheight); bitmapFactoryOptions.inSampleSize = inSampleSize; bitmapFactoryOptions.inJustDecodeBounds = false; bmap = BitmapFactory.decodeFile(picture.getAbsolutePath(), bitmapFactoryOptions); return bmap; } catch (Exception e) { e.printStackTrace(); return null; } }
PS:如果使用一个BitmapFactory.Options对象,要先把该对象的inJustDecodeBounds属性设置为true,inSampleSize设置完成后再设置为false。后面的是用来翻转图片的。
第二种方式:
public Bitmap getThumbImageBySize(String imgpath, int size, boolean adjustOrientation) { File file=new File(imgpath); FileInputStream fis = null; int filesize=0; try{ fis = new FileInputStream(file); filesize = fis.available(); Log.v("file length", ""+filesize); fis.close(); }catch(Exception ex){ Log.v("Read file error", ""+ex.getMessage()); } if(filesize/1024<size){ return BitmapFactory.decodeFile(imgpath); } // Revision: BitmapFactory.Options options = new BitmapFactory.Options(); // Set it false to not build the bitmap,just record its width and height options.inJustDecodeBounds = true; // Get the Options object by the path BitmapFactory.decodeFile(imgpath, options); int height = options.outHeight; int width = options.outWidth; Bitmap smallBitmap = null; double multiple = (float)(width*height*4)/(float)(size*1024); int inSampleSize = (int)Math.ceil(Math.sqrt(((float)filesize/1024.0)/(float)size)); options.inSampleSize=inSampleSize; options.inJustDecodeBounds = false; smallBitmap = BitmapFactory.decodeFile(imgpath, options); return smallBitmap; } }
原文地址:http://fancyyou.blog.51cto.com/4872763/1596283