zoukankan      html  css  js  c++  java
  • 图片压缩的方法

    参考下面的

    http://www.oschina.net/code/snippet_726985_22365

    http://gundumw100.iteye.com/blog/849729(好)

    /**
         * compress bitmap to less than long size,可以再研究
         * @param bitmap
         * @param long  size
         * @return compressed bitmap
         */
        public static Bitmap compressBitmap(Bitmap bitmap, long size ){
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100 , baos);//100表示不压缩,压缩后放在baos中
            Log.i("before compress", String.valueOf( baos.toByteArray().length/1024));
            
            if (bitmap==null|| baos.toByteArray().length<=size){
                Log.i("before", "bitmap null or < size");
                return bitmap;  //已经很小了
            }    
            
            int compressRatio=100; //压缩
            while (baos.toByteArray().length>size) {//如果压缩后大于100k,再压缩
                baos.reset();
                compressRatio=compressRatio-3;
                if(compressRatio<=10){
                    Log.i("compress", "break in while");
                    break;
                }        
                bitmap.compress(Bitmap.CompressFormat.JPEG,compressRatio , baos);
                Log.i("compress", "in while "+String.valueOf(baos.toByteArray().length/1024));
            }
            Log.i("after, baos ",String.valueOf(baos.toByteArray().length/1024));
            ByteArrayInputStream bois = new ByteArrayInputStream(baos.toByteArray());
            Bitmap newBitmap= BitmapFactory.decodeStream(bois,null,null);
            bitmap.recycle();
            return newBitmap;
        }
        
        public static long getSizeofBitmap(Bitmap bitmap) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 100表示不压缩质量
            long size = baos.toByteArray().length ;// 读出图片的kb大小
            return size;
        }
  • 相关阅读:
    Linux文档中翻页和搜索关键字
    windows安装mysql
    生成二维码和解析二维码
    powerdesigner通过er图生成mysql执行文件
    powerdesigner使用遇到的一些问题
    UnsupportedOperationException异常
    String[]和List的区别及相互转换
    @PostConstruct注解原理解析
    git强制更新并覆盖本地修改
    Dubbo架构与底层实现
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4050900.html
Copyright © 2011-2022 走看看