在Android中,对图片使用的内存是有限制的,加载的图片过大便出致使OOM问题。图像在加载过程当中,是把全部像素(即长*宽)加载到内存中,若是图片过大,便会致使java.lang.OutOfMemoryError问题,所以,在使用时要要加以注意。java
- private static int MAX_IMAGE_DIMENSION = 720;
-
- public Bitmap decodeFile(String filePath) throws IOException {
-
- Uri photoUri = Uri.parse(filePath);
- InputStream is = this.getContentResolver().openInputStream(photoUri);
- BitmapFactory.Options dbo = new BitmapFactory.Options();
- dbo.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(is, null, dbo);
- is.close();
-
- int rotatedWidth, rotatedHeight;
- rotatedWidth = dbo.outWidth;
- rotatedHeight = dbo.outHeight;
-
-
- Bitmap mCurrentBitmap = null;
- is = this.getContentResolver().openInputStream(photoUri);
- if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) {
- float widthRatio = ((float) rotatedWidth) / MAX_IMAGE_DIMENSION;
- float heightRatio = ((float) rotatedHeight) / MAX_IMAGE_DIMENSION;
- float maxRatio = Math.max(widthRatio, heightRatio);
-
- BitmapFactory.Options options = new BitmapFactory.Options();
-
- options.inSampleSize = (int) maxRatio;
-
- options.inPurgeable = true;
-
- options.inInputShareable = true;
-
- options.inPreferredConfig = Bitmap.Config.RGB_565;
- try {
-
- BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
-
-
- mCurrentBitmap = BitmapFactory.decodeStream(is, null, options);
- } else {
- mCurrentBitmap = BitmapFactory.decodeStream(is);
- }
- return mCurrentBitmap;
- }