照片压缩存储

来源:互联网 发布:什么叫智能网络电视 编辑:程序博客网 时间:2024/04/28 04:54

一般相机拍摄的照片大小为3-4M左右,这里因为需要完成将拍摄好的照片上传到服务器功能,所以需要将得到的照片进行压缩。这里演示就直接存放在SD卡中。

网上搜索了不少资料,得知可以使用:inSampleSize 设置图片的缩放比例。

但是,这里需要注意:

1)inJustDecodeBounds = true; 需要先设置为真,表示只获得图片的资料信息。如果此时检验bitmap会发现bitmap==null;

2)如果需要加载图片的时候,必须重新设置inJustDecodeBounds = false;

一、实现图片压缩(网上看到别人的,自己稍微修改了一下):

//压缩图片尺寸    public Bitmap compressBySize(String pathName, int targetWidth,              int targetHeight) {          BitmapFactory.Options opts = new BitmapFactory.Options();          opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等;          Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);        // 得到图片的宽度、高度;          float imgWidth = opts.outWidth;          float imgHeight = opts.outHeight;          // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;          int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);          int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);         opts.inSampleSize = 1;        if (widthRatio > 1 || widthRatio > 1) {              if (widthRatio > heightRatio) {                  opts.inSampleSize = widthRatio;              } else {                  opts.inSampleSize = heightRatio;              }          }          //设置好缩放比例后,加载图片进内容;          opts.inJustDecodeBounds = false;          bitmap = BitmapFactory.decodeFile(pathName, opts);          return bitmap;      }
二、将压缩后的图片存储于SD卡:
//存储进SD卡    public void saveFile(Bitmap bm, String fileName) throws Exception {        File dirFile = new File(fileName);          //检测图片是否存在        if(dirFile.exists()){              dirFile.delete();  //删除原图片        }          File myCaptureFile = new File(fileName);          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));          //100表示不进行压缩,70表示压缩率为30%        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);          bos.flush();          bos.close();      }  

0 0