<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在android中加载大图片,android系统会默认把图片加载到内存中,在去展示出来。</span>
android设备会给每一程序分配一个内存,一般大小为16M,手机不同分配的大小也不同,当加载一个大图片时会占用多少内存呢,首先要看你的图片的格式,是采RGB_565 = 2字节 ARBG_8888 = 4字节 ,,意思是一个像素点所占的字节。
例如:一个图片像素为 3648 * 2736 ,那么它的像素点 为3648 * 2736= 9980928 像素;所需要的内存为 9980928*2=19M ,加载这么一张大图片所要内存就19M,肯定会产生内存溢出。
那么怎么解决呢?
获得设备要展示的大小,之后等比例压缩。
1,第一步获得图片的元数据。
2,不要让他在内存中直接加载;
3,通过元数据 与你要展示的大小进行等比例压缩;
<span style="font-size:18px;"> // 根据路径把图片的宽和高取出来, 计算缩放比例
Options opts = new Options();
// 如果设置为true, 不去加载图片, 但是会把图片的元数据()取出来.
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
// 取出图片的宽和高
int picWidth = opts.outWidth;
int picHeight = opts.outHeight;
System.out.println("图片的宽和高: " + picWidth + " * " + picHeight);
// 得到手机屏幕的宽和高
Display display = getWindowManager().getDefaultDisplay();
// 屏幕的宽度
int screenWidth = display.getWidth();
// 屏幕的高度度
int screenHeight = display.getHeight();
int scaleWidth = picWidth / screenWidth;
int scaleHeight = picHeight / screenHeight;
int scale = scaleWidth > scaleHeight ? scaleWidth : scaleHeight;
// 按照缩放的比例加载图片
opts.inJustDecodeBounds = false;
opts.inSampleSize = scale; // 按照比例加载图片
Bitmap bitmap = BitmapFactory.decodeFile(path, opts);
iv.setImageBitmap(bitmap);</span>