• Android中图片压缩(质量压缩和尺寸压缩)


    关于Android 图片压缩的学习:

    自己总结分为质量压缩和像素压缩。质量压缩即:将Bitmap对象保存到对应路径下是所占用的内存减小,但是当你重新读取压缩后的file为Bitmap时,它所占用的内存并没有改变,它会改变其图像的位深和每个像素的透明度,也就是说JPEG格式压缩后,原来图片中透明的元素将消失,所以这种格式很可能造成失真。像素压缩:将Bitmap对象的像素点通过设置采样率,减少Bitmap的像素点,减小占用内存。两种压缩均可能对图片清晰度造成影响。

    (一)

    /**
    *
    * @description 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,
    * 特点是: File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变
    * 所谓的质量压缩,即为改变其图像的位深和每个像素的透明度,也就是说JPEG格式压缩后,原来图片中透明的元素将消失,所以这种格式很可能造成失真
    * @date 2015年8月25日
    * @param bmp
    * @param file
    */
    public static void compressBmpToFile(Bitmap bmp,File file) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int options = 80;
    bmp.compress(CompressFormat.JPEG, options, baos);
    while(baos.toByteArray().length/1024 > 100){
    baos.reset();
    options -= 10;
    bmp.compress(Bitmap.CompressFormat.JPEG, options,baos);
    }
    try {
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baos.toByteArray());
    fos.flush();
    fos.close();
    }
    catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }

      
    (二)

    /**
    *
    * @description 将图片从本地读到内存时,即图片从File形式变为Bitmap形式
    * 特点:通过设置采样率,减少图片的像素,达到对内存中的Bitmao进行压缩
    方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存
    * @date 2015年8月25日
    * @param image
    * @return
    */
    private Bitmap compressBmpFromBmp(String srcPath){
    BitmapFactory.Options newOptions = new BitmapFactory.Options();
    newOptions.inJustDecodeBounds = true;//只读边,不读内容
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOptions);

    newOptions.inJustDecodeBounds = false;
    int w = newOptions.outWidth;
    int h = newOptions.outHeight;
    float hh = 800f;
    float ww = 480f;
    int be = 1;
    if(w > h && w >ww){
    be = (int)(newOptions.outWidth/ww);
    }else if (w < h && h > hh) {
    be = (int)(newOptions.outHeight/hh);
    }
    if(be <= 0)
    be = 1;
    newOptions.inSampleSize = be;//设置采样率
    newOptions.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设
    newOptions.inPurgeable = true;//同时设置才会有效
    newOptions.inInputShareable = true;//当系统内存不够时候图片会自动被回收

    bitmap = BitmapFactory.decodeFile(srcPath, newOptions);
    return bitmap;

    }

  • 相关阅读:
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3
    display:inline-block的运用
    图解单片机8位PWM、16位PWM中“位”的含义!
    UVA10006
    [置顶] CF 86D Powerful array 分块算法入门,n*sqrt(n)
    俗人解释 三维渲染 在工作过程
    HDU 4414 Finding crosses(dfs)
    Codeforces 35E Parade 扫描线 + list
    hdu 4374 单调队列
    LeetCode OJ平台Sort Colors讨论主题算法
  • 原文地址:https://www.cnblogs.com/yuanting/p/4758125.html
Copyright © 2020-2023  润新知