国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

圖片的壓縮處理

2019-11-09 18:20:29
字體:
來源:轉載
供稿:網友

在處理圖片顯示時,如果圖片顯示較少,一般沒有什么問題。但如果一次加載很多圖片,很有可能報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表示壓縮一半。

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

 

 

 

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 衡山县| 安康市| 长丰县| 柯坪县| 林口县| 绥滨县| 丹东市| 大关县| 启东市| 雅江县| 交城县| 赤壁市| 清涧县| 常山县| 长岛县| 安化县| 黑水县| 浦东新区| 玉林市| 敦煌市| 日土县| 内江市| 石河子市| 垫江县| 潞城市| 古田县| 保山市| 富蕴县| 龙海市| 轮台县| 和平县| 宜川县| 新平| 庆元县| 磐石市| 连云港市| 奈曼旗| 天水市| 信丰县| 大厂| 珠海市|