用decodeFileDescriptor()来生成bimap比decodeFile()省内存
FileInputStream is = = new FileInputStream(path); bmp = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
Bitmap bmp = BitmapFactory.decodeFile(imageFile, opts); imageView.setImageBitmap(bmp);
原因:
查看BitmapFactory的源码,对比一下两者的实现,可以发现decodeFile()最终是以流的方式生成bitmap
decodeFile源码:
public static Bitmap decodeFile(String pathName, Options opts) { Bitmap bm = null; InputStream stream = null; try { stream = new FileInputStream(pathName); bm = decodeStream(stream, null, opts); } catch (Exception e) { /* do nothing. If the exception happened on open, bm will be null. */ } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // do nothing here } } } return bm; }
decodeFileDescriptor的源码,可以找到native本地方法decodeFileDescriptor,通过底层生成bitmap
decodeFileDescriptor源码:
public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) { if (nativeIsSeekable(fd)) { Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts); if (bm == null && opts != null && opts.inBitmap != null) { throw new IllegalArgumentException("Problem decoding into existing bitmap"); } return finishDecode(bm, outPadding, opts); } else { FileInputStream fis = new FileInputStream(fd); try { return decodeStream(fis, outPadding, opts); } finally { try { fis.close(); } catch (Throwable t) {/* ignore */} } } } private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts);