android 图片压缩 笔记

来源:互联网 发布:php跳转到指定页面代码 编辑:程序博客网 时间:2024/06/17 11:14
   两个重要的方法。和代码  
质量压缩。--像素不变  ---该方法是把bimmap生成文件。---质量压缩读出来的bitmap大小不变。所以不能用于直接显示

    /**
     * 质量压缩。
     * @param bmp  ---- 需要压缩的bmp
     * @param path ---- 压缩之后储存的文件名字 -- 全部路径
     * @param options - 需要要压缩到百分之几十 
     */
    public static void compressBmpToFile(Bitmap bmp,String path , int options){
        File mFile = new File(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
//        options = 30;//30不会失真 
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);  
//        while (baos.toByteArray().length / 1024 > 500) {   这里的循环压缩是没有用的
//            baos.reset();  
//            options -= 2;  
//            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);  
//        }  
        try {  
            FileOutputStream fos = new FileOutputStream(mFile);  
            fos.write(baos.toByteArray());  
            fos.flush();  
            fos.close(); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

尺寸压缩/比例压缩 ---读出来的bitmap较小。可以用于内存优化
--该方法是把文件读出来。但不是直接读。而是压缩了再读。生成bitmap  --这个bitmap可以重新写回sd卡。也可以显示

    /**
     * 图片按比例大小压缩方法---也就是尺寸压缩。说到底。就是通过 newOpts.inSampleSize 来改变他的大小。
     * 但是decode呢只decode 计算长宽。不分配空间。再通过计算出来的inSampleSize大小。重新decode。--计算inSampleSize该方法里有
     * 所以说在显示大图的时候。不能直接decode。需要计算出一个inSampleSize值。再decode出来bitmap。用于显示
     * 
     * @param srcPath (根据路径获取图片并压缩)
     * @return bitmap
     */  
    public static Bitmap getimage(String srcPath) {  

        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        // 开始读入图片,此时把options.inJustDecodeBounds 设回true了  
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空  

        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为  
        float hh = 800f;// 这里设置高度为800f  
        float ww = 480f;// 这里设置宽度为480f  
        // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
        int be = 1;// be=1表示不缩放  
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放  
            be = (int) (newOpts.outWidth / ww);  
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放  
            be = (int) (newOpts.outHeight / hh);  
        }  
        if (be <= 0)  
            be = 1;  
        newOpts.inSampleSize = be;// 设置缩放比例  
        // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
        return bitmap;// 压缩好比例大小后再进行质量压缩  
    }  


1 0
原创粉丝点击