Android开发压缩图片

在Android开发中为了防止内存溢出,在显示图片时通常都对图片进行不同的压缩,以下就是压缩的代码:

第一步:先通过对图片大小及手机屏幕尺寸的计算得出来的值然后对图片的尺寸进行缩小,在这时尺寸压缩后,

             在产生Bitmap时就不会出现OutOfMemoryException异常了。尺寸压缩使用Options的inSampleSize属性

             来控制缩放比例。

第二步:压缩图片质量,根据文件大小来判断压缩程度。

  1. public Bitmap createNewBitmapAndCompressByFile(String filePath, int wh[]) {  
  2.         int offset = 100;  
  3.         File file = new File(filePath);  
  4.         long fileSize = file.length();  
  5.         if (200 * 1024 < fileSize && fileSize <= 1024 * 1024)  
  6.             offset = 90;  
  7.         else if (1024 * 1024 < fileSize)  
  8.             offset = 85;  
  9.   
  10.         BitmapFactory.Options options = new BitmapFactory.Options();  
  11.         options.inJustDecodeBounds = true// 为true里只读图片的信息,如果长宽,返回的bitmap为null   
  12.         options.inPreferredConfig = Bitmap.Config.ARGB_8888;  
  13.         options.inDither = false;  
  14.         /** 
  15.          * 计算图片尺寸 //TODO 按比例缩放尺寸 
  16.          */  
  17.         BitmapFactory.decodeFile(filePath, options);  
  18.   
  19.         int bmpheight = options.outHeight;  
  20.         int bmpWidth = options.outWidth;  
  21.         int inSampleSize = bmpheight / wh[1] > bmpWidth / wh[0] ? bmpheight / wh[1] : bmpWidth / wh[0];  
  22.         // if(bmpheight / wh[1] < bmpWidth / wh[0]) inSampleSize = inSampleSize * 2 / 3;//TODO 如果图片太宽而高度太小,则压缩比例太大。所以乘以2/3   
  23.         if (inSampleSize > 1)  
  24.             options.inSampleSize = inSampleSize;// 设置缩放比例   
  25.         options.inJustDecodeBounds = false;  
  26.   
  27.         InputStream is = null;  
  28.         try {  
  29.             is = new FileInputStream(file);  
  30.         } catch (FileNotFoundException e) {  
  31.             return null;  
  32.         }  
  33.         Bitmap bitmap = null;  
  34.         try {  
  35.             bitmap = BitmapFactory.decodeStream(is, null, options);  
  36.         } catch (OutOfMemoryError e) {  
  37.               
  38.             System.gc();  
  39.             bitmap = null;  
  40.         }  
  41.         if (offset == 100)  
  42.             return bitmap;// 缩小质量   
  43.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  44.         bitmap.compress(Bitmap.CompressFormat.JPEG, offset, baos);  
  45.         byte[] buffer = baos.toByteArray();  
  46.         options = null;  
  47.         if (buffer.length >= fileSize)  
  48.             return bitmap;  
  49.         return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);  
  50.     }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值