图片的压缩

来源:互联网 发布:韩国淘宝女模特排行榜 编辑:程序博客网 时间:2024/05/21 22:45
在前面的GGBA颜色制作特效这篇笔记中,说了图片由像素组成,像素由
色相,饱和度,亮度组成。当图片的像素不变时,把它读取到内存中不是不会节省开销的。

这里有一个压缩质量的方法来压缩图片,要把图片压缩到100k以下

public static void compressBmpToFile(Bitmap bmp,File file){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        int options = 80;  
        bmp.compress(Bitmap.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 (Exception e) {  
            e.printStackTrace();  
        }  
    }  
如果原来你读取图片时发生内存溢出,然后高兴的去调用这个方法,你会发现,并没什么卵用。
还是照样溢出。
这是为什么呢?这个图片压缩的是质量,图片的长宽没变,然后得像素不变,然后得出不会节省内存的结论。
所以该溢出还是要溢出。
那么是什么让图片质量下降了?官方文档说这是像素组成元素中的亮度被抛弃的缘故。所以质量压缩会让
图变得模糊。

那么怎么才能降低像素呢,那自然是调整长宽。
长宽变小了,像素自然低了。

private Bitmap compressImageFromFile(String srcPath) {  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        newOpts.inJustDecodeBounds = true;//只读边,不读内容  ,这个很重要
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
  
        newOpts.inJustDecodeBounds = false;  
        int w = newOpts.outWidth;  
        int h = newOpts.outHeight;  
        float hh = 800f;//  
        float ww = 480f;//  
        int 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;//设置采样率  
          
        newOpts.inPreferredConfig = Config.ARGB_8888;//该模式是默认的,可不设  
        newOpts.inPurgeable = true;// 同时设置才会有效  
        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收  
          
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  

        return bitmap;  
    }  








0 0