在處理圖片顯示時,如果圖片顯示較少,一般沒有什么問題。但如果一次加載很多圖片,很有可能報oom錯誤。比如照片墻,viewpager同時顯示幾十張圖片,所有有必要了解圖片的壓縮處理。
1.新建一個函數,封裝圖片的壓縮處理。
PRivate Bitmap decodeBitmapFromFile(String absolutePath, int reqWidth, int reqHeight) { 參數分別是:圖片的絕對路徑,圖片設置的寬度,圖片設置的高度
Bitmap bm = null; // First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options. inJustDecodeBounds = true ;
BitmapFactory. decodeFile(absolutePath, options); // Calculate inSampleSize
options. inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set
options. inJustDecodeBounds = false ;
bm = BitmapFactory. decodeFile(absolutePath, options);
return bm; }
當把options. inJustDecodeBounds 設置為true時,BitmapFactory. decodeFile(absolutePath, options并不生成bitmap,而是獲取了圖片的寬度和高度,然后設置options. inSampleSize設置縮放比例,讓后就可以得到壓縮大小的圖片。
private int calculateInSampleSize(Options options, int reqWidth, int reqHeight) { // Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math. round((float)height / ( float)reqHeight);
} else {
inSampleSize = Math. round((float)width / ( float)reqWidth);
}
}
return inSampleSize;
}
這里的圖片壓縮只是壓縮了圖片的大小,如果需要壓縮圖片的質量,可以用新的函數。
private Bitmap compressImage(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即清空baosoptions -= 10;//每次都減少10image.compress(Bitmap.CompressFormat.JPEG, options, baos);//這里壓縮options%,把壓縮后的數據存放到baos中}ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把壓縮后的數據baos存放到ByteArrayInputStream中Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream數據生成圖片return bitmap;}
主要是通過image.compress(Bitmap.CompressFormat.JPEG, 100, baos);來壓縮圖片的質量,其中100表示不壓縮,50表示壓縮一半。
圖片壓縮就是這些了,其實比較簡單。
新聞熱點
疑難解答