android 中图片的压缩处理

来源:互联网 发布:淘宝店铺能不能转让 编辑:程序博客网 时间:2024/06/11 01:26
Android中图片问题的处理(一)
(要加载的图片在本地)
1.如何更有效的加载大图片
   每个应用程序所能利用的运行内存空间是有限的(16M),所以在加载大图片是一定要提防内存溢出问题
  例如,你加载了一张2592*1936像素的图片,如果这个图片的类型是ARGB_8888,那么加载这张图片所需要的内存
  大小是19M,已经超出了所允许的16M的大小


常用图片类型:RGB_565   16位(2个字节)
 ARGB_4444   (2个字节)
 ARGB_8888   (4个字节),,这些是每个像素所占用的大小




如果在你的应用中要加载的图片是用手机的照相机拍下的,这时候需要注意,很有可能导致内存溢出(并非一定)
最好的办法就是将图片进行等比例缩放(不会带来任何坏处)
  


  步骤:
1.  得到图片的类型和规模BitmapFactory.Options options = new BitmapFactory.Options();//首先将该参数设置为true,避免在加载图片时,为给图片分配内存,也就是说,设置为true时,虚拟机是//不会给该图片分配内存的,所以,得到的图片时null,这段代码并非要的到图片本身,他只是简单//的获取该图片的规模,(高度,宽度,类型)        options.inJustDecodeBounds = true;        BitmapFactory.decodeResource(getResources(), R.id.myimage, options);        int imageHeight = options.outHeight;        int imageWidth = options.outWidth;        String imageType = options.outMimeType;2。加载一个缩放版本的图片到内存public static int calculateInSampleSize(            BitmapFactory.Options options, int reqWidth, int reqHeight) {    // Raw height and width of image    final int height = options.outHeight;    final int width = options.outWidth;    int inSampleSize = 1;//缩放比例    if (height > reqHeight || width > reqWidth) {        // Calculate ratios of height and width to requested height and width        final int heightRatio = Math.round((float) height / (float) reqHeight);        final int widthRatio = Math.round((float) width / (float) reqWidth);        // Choose the smallest ratio as inSampleSize value, this will guarantee        // a final image with both dimensions larger than or equal to the        // requested height and width.        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;    }    return inSampleSize;}public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,        int reqWidth, int reqHeight) {    // First decode with inJustDecodeBounds=true to check dimensions    final BitmapFactory.Options options = new BitmapFactory.Options();    options.inJustDecodeBounds = true;    BitmapFactory.decodeResource(res, resId, options);    // Calculate inSampleSize    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);    // Decode bitmap with inSampleSize set    options.inJustDecodeBounds = false;    return BitmapFactory.decodeResource(res, resId, options);}

0 0
原创粉丝点击