当前位置: 移动技术网 > IT编程>移动开发>Android > Android中3种图片压缩处理方法

Android中3种图片压缩处理方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

救僵清道夫下载,sityle,欧女兽交

android中图片的存在形式:

1:文件形式:二进制形式存在与硬盘中。
2:流的形式:二进制形式存在与内存中。
3:bitmap的形式

三种形式的区别:
文件形式和流的形式:对图片体积大小并没有影响。也就是说,如果你手机sd卡上的图片通过流的形式读到内存中,在内存中的大小也是原图的大小。
注意:不是bitmap的形式。
bitmap的形式:图片占用的内存会瞬间变大。
以下是代码的形式:

    

 /**
   * 图片压缩的方法总结
   */

  /*
   * 图片压缩的方法01:质量压缩方法
   */
  private bitmap compressimage(bitmap beforbitmap) {

    // 可以捕获内存缓冲区的数据,转换成字节数组。
    bytearrayoutputstream bos = new bytearrayoutputstream();
    if (beforbitmap != null) {
      // 第一个参数:图片压缩的格式;第二个参数:压缩的比率;第三个参数:压缩的数据存放到bos中
      beforbitmap.compress(compressformat.jpeg, 100, bos);
      int options = 100;
      // 循环判断压缩后的图片是否是大于100kb,如果大于,就继续压缩,否则就不压缩
      while (bos.tobytearray().length / 1024 > 100) {
        bos.reset();// 置为空
        // 压缩options%
        beforbitmap.compress(compressformat.jpeg, options, bos);
        // 每次都减少10
        options -= 10;

      }
      // 从bos中将数据读出来 存放到bytearrayinputstream中
      bytearrayinputstream bis = new bytearrayinputstream(
          bos.tobytearray());
      // 将数据转换成图片
      bitmap afterbitmap = bitmapfactory.decodestream(bis);
      return afterbitmap;
    }
    return null;
  }

  /*
   * 图片压缩方法02:获得缩略图
   */
  public bitmap getthumbnail(int id) {
    // 获得原图
    bitmap beforebitmap = bitmapfactory.decoderesource(
        mcontext.getresources(), id);
    // 宽
    int w = mcontext.getresources()
        .getdimensionpixeloffset(r.dimen.image_w);
    // 高
    int h = mcontext.getresources().getdimensionpixelsize(r.dimen.image_h);

    // 获得缩略图
    bitmap afterbitmap = thumbnailutils
        .extractthumbnail(beforebitmap, w, h);
    return afterbitmap;

  }

  /**
   * 图片压缩03
   * 
   * @param id
   *      要操作的图片的大小
   * @param newwidth
   *      图片指定的宽度
   * @param newheight
   *      图片指定的高度
   * @return
   */
  public bitmap compressbitmap(int id, double newwidth, double newheight) {
    // 获得原图
    bitmap beforebitmap = bitmapfactory.decoderesource(
        mcontext.getresources(), id);
    // 图片原有的宽度和高度
    float beforewidth = beforebitmap.getwidth();
    float beforeheight = beforebitmap.getheight();

    // 计算宽高缩放率
    float scalewidth = 0;
    float scaleheight = 0;
    if (beforewidth > beforeheight) {
      scalewidth = ((float) newwidth) / beforewidth;
      scaleheight = ((float) newheight) / beforeheight;
    } else {
      scalewidth = ((float) newwidth) / beforeheight;
      scaleheight = ((float) newheight) / beforewidth;
    }

    // 矩阵对象
    matrix matrix = new matrix();
    // 缩放图片动作 缩放比例
    matrix.postscale(scalewidth, scaleheight);
    // 创建一个新的bitmap 从原始图像剪切图像
    bitmap afterbitmap = bitmap.createbitmap(beforebitmap, 0, 0,
        (int) beforewidth, (int) beforeheight, matrix, true);
    return afterbitmap;

  }

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网