圖片壓縮代碼


此壓縮代碼,直接傳入路徑即可完成壓縮,調用getImage()方法傳入圖片路徑即可。

代碼如下:

 /*
     * @param srcPath
     * @return
     * 圖片比例大小壓縮
     */
    private void 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 = 480f;//這里設置高度為480f
        float ww = 800f;//這里設置寬度為800f
        //縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
        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);
        compressImage(srcPath,bitmap);//壓縮好比例大小后再進行質量壓縮
    }

    /*
     * @param image
     * @return
     * 圖片質量壓縮
     */
    private void compressImage(String path,Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這里100表示不壓縮,把壓縮后的數據存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) {  //循環判斷如果壓縮后圖片是否大於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數據生成圖片
        saveMyBitmap(bitmap,path);
    }

    /*
     * @param mBitmap
     * @param path
     * 保存壓縮的圖片
     */
    public void saveMyBitmap(Bitmap mBitmap,String path)  {
        File f = new File(path);
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM