Android Bitmap壓縮圖像

壓縮圖片的方法:

//            // 從選取相冊的Activity中返回後
//            Uri imageUri = data.getData();
//            String[] filePathColumns = {MediaStore.Images.Media.DATA};
//            Cursor c = getContentResolver().query(imageUri, filePathColumns, null, null, null);
//            c.moveToFirst();
//            int columnIndex = c.getColumnIndex(filePathColumns[0]);
//            String imagePath = c.getString(columnIndex);
//            c.close();
            // 相機的Activity中返回後
            String imagePath = imageUri.getPath();

            // 設置參數
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; // 只獲取圖片的大小信息,而不是將整張圖片載入在內存中,避免內存溢出
            BitmapFactory.decodeFile(imagePath, options);
            int height = options.outHeight;
            int width= options.outWidth;
            Log.w("TAG", "原來size: " + options.outMimeType + " width: " + width + " heigth:" + height); // 輸出圖像數據
            int inSampleSize = 2; // 默認像素壓縮比例,壓縮爲原圖的1/2
            int minLen = Math.min(height, width); // 原圖的最小邊長
            if(minLen > 100) { // 如果原始圖像的最小邊長大於100dp(此處單位我認爲是dp,而非px                float ratio = (float)minLen / 100.0f; // 計算像素壓縮比例
                inSampleSize = (int)ratio;
            }
            options.inJustDecodeBounds = false; // 計算好壓縮比例後,這次可以去加載原圖了
            options.inSampleSize = inSampleSize; // 設置爲剛纔計算的壓縮比例
            Bitmap bm = BitmapFactory.decodeFile(imagePath, options); // 解碼文件
            Log.w("TAG", "yasuohsize: " + bm.getByteCount() + " width: " + bm.getWidth() + " heigth:" + bm.getHeight()); // 輸出圖像數據
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageBitmap(bm);

發佈了45 篇原創文章 · 獲贊 17 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章