Android---加载图片 解决图片过大致使的内存溢出问题

图片的处理

  • 图片的总大小 = 图片的总像素 * 每一个像素的大小web

  • BMP 无损格式svg

    • 位图
      • 单色(黑、白)、1六、25六、24(RGB)
  • 单色spa

    • 每一个像素只能表示两钟颜色,只须要使用一个长度为1的二进制数字便可,一个像素占用1/8个字节
  • 16色code

    • 每一个像素能够表示16种颜色,那么须要16个数字,0-15,二进制是 0000-1111长度为4的二进制数字,每一个像素占用1/2个字节
  • 256色xml

    • 每一个像素能够表示256种颜色,那么须要256个数字,也就是0-255,二进制是 0000 0000 - 1111 1111 长度为8的二进制数字,每一个像素占用1个字节
  • 24位:对象

    • 每一个像素能表示的颜色用一个24位的二进制数字表示,16777215,每一个像素占用3个字节
    • RGB
      • R:Red 取值范围0-55
      • G:Green 取值范围0-255
      • B:Blue 取值范围0-255
  • Android中使用的是ARGB 每一个像素占用4个字节图片

    • A:alpha 透明度 取值范围 0-255

加载图片

  • 图片像素过大形成内存溢出
  • 解决方案:先缩放图片,再加载
    • 将图片缩放至屏幕大小
  • 计算缩放比例
    • 例如:
    • 图片宽高:2400*3200
    • 屏幕宽高:320*480
    • 宽的缩放比例:2400/320=7
    • 高的所犯高比例:3200/480=6
    • 宽高的缩放比例采用统一个值7 使用大的那个
  • 缩放方法:内存

    • 使用Bitmapfactory.Optionsget

      • OPtions opts = new Options ();
      • opts.inJustDecodeBounds = true ;string

        • 设置为true时,BitmapFactory的decodeFile(String path,Options opt)并不会返回一个Bitmap对象,可是会返回图片的大小 (宽、高)
      • //拿到图片的宽高

int width = opts.outWidth;
int height = opts.outHeight;
* //获取屏幕宽高
Display dp = getWindowManager().getDefaultDisplay();
int screenWidth = dp.getWidth();
int screenHeight = dp.getHeight();
* //计算缩放比例
int scaleWidth = width / screenWidth;
int scaleHeight = height / screenHeight;
int scale = 1;
* //肯定使用哪一个缩放比例  使用大的那个
if (scaleWidth >= scaleHeight && scaleWidth > 0) {
    scale = scaleWidth;
    } else if (scaleWidth < scaleHeight && scaleHeight > 0) {
        scale = scaleHeight;
}
* //设置缩放比例
opts.inSampleSize = scale;
opts.inJustDecodeBounds = false;

Bitmap bm = BitmapFactory.decodeFile("sdcard/Download/hello.png", opts);
iv.setImageBitmap(bm);