android 中图片的压缩处理

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值