1. 程式人生 > >Andriod 無損高質量壓縮

Andriod 無損高質量壓縮

將11M的圖片壓縮為3M,質量沒怎麼下降。
分為兩步:1,壓縮圖片大小(降了一半) 
         2,壓縮圖片質量
程式碼如下:
public class CompressImageUyil {


    /** zj
     * 無損高質量壓縮
     * @param sFile  圖片地址
     * @param dFile   壓縮後地址
     * @param size    壓縮大小
     */
    public static void CompressImage(String sFile, String dFile ,int size){
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inJustDecodeBounds=true;                              // 這裡要設定Options.inJustDecodeBounds=true,這時候decode的bitmap為null,只是把圖片的寬高放在Options裡
        Bitmap bitmap=BitmapFactory.decodeFile(sFile,options);      //此時返回bm為空
        options.inJustDecodeBounds = false;
        options.inSampleSize=2;//按照比率壓縮50%
        bitmap = BitmapFactory.decodeFile(sFile, options);     //重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了
        compressImage(bitmap,size,dFile);
    }



    private static void compressImage(Bitmap image,int size,String dFile) {
        File file = new File(dFile);                                     //將要儲存圖片的路徑
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos); //質量壓縮方法,這裡100表示不壓縮,把壓縮後的資料存放到baos中
        int options = 100;
        while ( baos.toByteArray().length >(size*1024)) {             //迴圈判斷如果壓縮後圖片是否大於size kb,大於繼續壓縮
            Log.d("compressImage", "compressImage: "+baos.toByteArray().length+"====>"+size*1024);
            baos.reset();                                             //重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos); //這裡壓縮options%,把壓縮後的資料存放到baos中
            options -= 5;//每次都減少10
        }
        try {
            FileOutputStream bos = new FileOutputStream(file);
            baos.writeTo(bos);
            bos.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}