日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

图片的压缩处理

發布時間:2024/4/15 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 图片的压缩处理 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在處理圖片顯示時,如果圖片顯示較少,一般沒有什么問題。但如果一次加載很多圖片,很有可能報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即清空baos
options -= 10;//每次都減少10
image.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表示壓縮一半。

圖片壓縮就是這些了,其實比較簡單。

?

?

?

?

總結

以上是生活随笔為你收集整理的图片的压缩处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。