图像压缩,避免OOM

来源:互联网 发布:微波炉有害 知乎 编辑:程序博客网 时间:2024/06/11 20:13

请注明出处:http://blog.csdn.net/daogepiqian/article/details/50484132

接着上一篇:

压缩图像:

首先判断file.length()是否超过所设定的最大值,超过了就需要压缩,

BitmapFactory.Options optGetPixel = new BitmapFactory.Options();
     optGetPixel.inJustDecodeBounds = true;
     BitmapFactory.decodeFile(strFromFile, optGetPixel);

optGetPixel.outWidth或 optGetPixel.outHeight 超出了给定的边长,就先进行尺寸压缩,

最后保存成文件时检测文件大小,如果文件大小超过MAX_IMAGE_FILE_SIZE,压缩质量再保存。

代码如下:


public void setImage(String path) {

  BitmapFactory.Options optGetPixel = new BitmapFactory.Options();
  optGetPixel.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(path, optGetPixel);
  int inSampleSize = getInSampleSizeWithFloor(optGetPixel.outWidth,
    optGetPixel.outHeight, 800);
  optGetPixel.inSampleSize = inSampleSize;
  optGetPixel.inJustDecodeBounds = false;
  optGetPixel.inPreferredConfig = Bitmap.Config.RGB_565;// 该模式下内存相对较小。ARGB_x多了一位透明值,这里的图片不需要,同时也为了避免OOM。
  fianBitmap = BitmapFactory.decodeFile(path, optGetPixel);
    
  clipedImagePath = null;
  clipedImagePath = getCapturePictureFilesPath(this);
  clipedImagePath = clipedImagePath + TEMP_AVATAR_FILE;// 涓存椂澶村儚鏂囦欢鍚�
  
  boolean suc = compressBitmapToFile(clipedImagePath, fianBitmap,
    2 * 1024 * 1024);
  
  headimage.setImageBitmap(fianBitmap);
 }

 private int getInSampleSizeWithFloor(int with, int height, int max) {
  int ret = 1;
  if (with > max || height > max) {// 需要缩放尺寸
   int maxSide = with > height ? with : height;
   int targetMaxSide = getTargetMaxSizeWithFloor(maxSide, max);
   ret = maxSide / targetMaxSide;
  }
  return ret;
 }

 private int getTargetMaxSizeWithFloor(int maxSide, int max) {
  int targetMaxSide = maxSide;
  if (maxSide > max && maxSide / 2 >= max) {
   targetMaxSide = maxSide / 2;
   if (targetMaxSide > max) {
    targetMaxSide = getTargetMaxSizeWithFloor(targetMaxSide, max);
   }
  }
  return targetMaxSide;
 }

public boolean compressBitmapToFile(String strFromFile, Bitmap bmp, int max) {
  File file = new File(strFromFile);
  if (file != null && file.exists() && file.isFile()) {
   file.delete();
  }
  ByteArrayOutputStream baos = null;
  FileOutputStream fos = null;
  try {
   baos = new ByteArrayOutputStream();
   int options = 80;// 从80开始,文件大于最大值,每次压缩10。
   bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
   while (baos.toByteArray().length > max) {
    baos.reset();
    options -= 10;
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
   }
   fos = new FileOutputStream(file);
   fos.write(baos.toByteArray());
   fos.flush();
   return true;
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (baos != null) {
     baos.close();
    }
   } catch (IOException e) {
   }
   try {
    if (fos != null) {
     fos.close();
    }
   } catch (IOException e) {
   }
  }
  return false;
 }

请注明出处:http://blog.csdn.net/daogepiqian/article/details/50484132

0 0
原创粉丝点击