zoukankan      html  css  js  c++  java
  • Android 图片压缩

    图片的压缩方式区分

    质量压缩和尺寸压缩。
    

    质量压缩是在保持像素的前提下改变图片的位深及透明度等,来达到压缩图片的目的,经过它压缩的图片文件大小会有改变,但是导入成bitmap后占得内存是不变的。因为要保持像素不变,所以它就无法无限压缩,到达一个值之后就不会继续变小了。显然这个方法并不适用与缩略图,其实也不适用于想通过压缩图片减少内存的适用,仅仅适用于想在保证图片质量的同时减少文件大小的情况而已

    尺寸压缩是压缩图片的像素,一张图片所占内存的大小 图片类型*宽*高,通过改变三个值减小图片所占的内存,防止OOM,当然这种方式可能会使图片失真

    质量压缩:

    public Bitmap compressImage(Bitmap image,int imageSize) {  
    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中  
            int options = 100;  
            while ( baos.toByteArray().length / 1024>imageSize) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩         
                baos.reset();//重置baos即清空baos  
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中  
                options -= 10;//每次都减少10  
            }  
            ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
            return bitmap;  
        } 
    

    尺寸压缩:

    public void scalePic(int reqWidth,int reqHeight) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);
            options.inSampleSize = PhotoUtil.calculateInSampleSize(options, reqWidth,reqHeight);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.demo, options);
    
            postInvalidate();
        }
    
    

    public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
            if (height > reqHeight || width > reqWidth) {
                final int heightRatio = Math.round((float) height / (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            return inSampleSize;
        }
    
    

    根据具体需求也可以两种压缩方式结合使用

  • 相关阅读:
    dcokee 安装 nginx
    docker 私有仓库
    docker下的images 保存和导出
    mybatis-puls 字段为null时候的更新问题
    MyBatis-Plus的一些问题
    60万数据的表添加索引查询的速度
    Velocity 模板引擎的应用
    什么是javabean及其用法
    java中this和super关键字的使用
    Windows-AutoHotkey-常用代码保存
  • 原文地址:https://www.cnblogs.com/ysmintor/p/5223649.html
Copyright © 2011-2022 走看看