[关闭]
@guhuizaifeiyang 2015-11-07T04:34:17.000000Z 字数 1478 阅读 1082

Android解析大图

Android开发


通常,解析图像会用到BitmapFactory类中的decodeFile方法来获得一个Bitmap对象。但当图像很大时,就会出现OOM(Out of Memory)。这时就需要用到BitmapFactory.Options,需要设置的有BitmapFactory.inJustDecodeBoundsBitmapFactory.inSampleSize

解析图像主要分为两步:
1. 获取图片的宽高,这里要设置Options.inJustDecodeBounds=true,当这个属性为true的时候,我们就可以禁止系统加载图片到内存,但是Options参数中的图片宽高、类型等属性已经被赋值了,这样,我们就实现了不使用内存就获取图片的属性。
2. 设置合适的压缩比例inSampleSize,这个属性可以设置图片的缩放比例,例如一张1000 X 1000像素的图片,设置inSampleSize为5,意思就是把这个图片缩放到了五分之一,即200 X 200 。

简单流程图:

Created with Raphaël 2.1.2StartBitmap path,width,heightdecodeFile(inJustDecodeBounds=true)calculate inSampleSizedecodeFile(inJustDecodeBounds=false)End

代码:

  1. public Bitmap decodeSampledBitmapFromSD(String path, int reqWidth, int reqHeight) {
  2. Bitmap bm = null;
  3. // First decode with inJustDecodeBounds=true to check dimensions
  4. final BitmapFactory.Options options = new BitmapFactory.Options();
  5. options.inJustDecodeBounds = true;
  6. BitmapFactory.decodeFile(path, options);
  7. // Calculate inSampleSize
  8. options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
  9. // Decode bitmap with inSampleSize set
  10. options.inJustDecodeBounds = false;
  11. bm = BitmapFactory.decodeFile(path, options);
  12. return bm;
  13. }
  14. // 计算SampleSize的方法有很多,这是其中一种比较简单的
  15. public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
  16. final int height = options.outHeight;
  17. final int width = options.outWidth;
  18. int inSampleSize = 1;
  19. if (height > reqHeight || width > reqWidth) {
  20. if (width > height) {
  21. inSampleSize = Math.round((float) height
  22. / (float) reqHeight);
  23. } else {
  24. inSampleSize = Math.round((float) width / (float) reqWidth);
  25. }
  26. }
  27. return inSampleSize;
  28. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注