Bitmap 中 decodeFileDescriptor(),decodeFile()两个方法对比
用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源码
- 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;
}
查看BitmapFactory的源码,对比一下两者的实现,可以发现decodeFile()最终是以流的方式生成bitmap
- decodeFileDescriptor源码
1. public static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, Options opts) {
2. if (nativeIsSeekable(fd)) {
3. Bitmap bm = nativeDecodeFileDescriptor(fd, outPadding, opts);
4. if (bm == null && opts != null && opts.inBitmap != null) {
5. throw new IllegalArgumentException("Problem decoding into existing bitmap");
6. }
7. return finishDecode(bm, outPadding, opts);
8. } else {
9. FileInputStream fis = new FileInputStream(fd);
10. try {
11. return decodeStream(fis, outPadding, opts);
12. } finally {
13. try {
14. fis.close();
15. } catch (Throwable t) {/* ignore */}
16. }
17. }
18. }
19.
20. private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,Rect padding, Options opts);
decodeFileDescriptor的源码,可以找到native本地方法decodeFileDescriptor,通过底层生成bitmap