Android Bitmap壓縮方式分析
創(chuàng)新互聯(lián)公司是一家專注于網站制作、網站設計與策劃設計,湘潭縣網站建設哪家好?創(chuàng)新互聯(lián)公司做網站,專注于網站建設十多年,網設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:湘潭縣等地區(qū)。湘潭縣做網站價格咨詢:13518219792
在網上調查了圖片壓縮的方法并實裝后,大致上可以認為有兩類壓縮:質量壓縮(不改變圖片的尺寸)和尺寸壓縮(相當于是像素上的壓縮);質量壓縮一般可用于上傳大圖前的處理,這樣就可以節(jié)省一定的流量,畢竟現(xiàn)在的手機拍照都能達到3M左右了,尺寸壓縮一般可用于生成縮略圖。
在Android開發(fā)中我們都會遇到在一個100*100的ImageView上顯示一張過大的圖片,如果直接把這張圖片顯示上去對我們應用沒有一點好處反而存在OOM的危險,所以我們有必要采用一種有效壓縮方式來顯示上去。
private void calculateBitmapInSimpleSize() { Bitmap _bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage); getBitmapDatas(_bitmap); BitmapFactory.Options optioins = new BitmapFactory.Options(); optioins.inJustDecodeBounds = true; // optioins.inPreferredConfig = Bitmap.Config.RGB_565;//11158560 optioins.inPreferredConfig = Bitmap.Config.ARGB_8888;//22317120 BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins); int reqWidth = optioins.outWidth; int reqHeight = optioins.outHeight; Log.w(TAG, "reqWidth = " + reqWidth); Log.w(TAG, "reqHeight = " + reqHeight); int inSampleSize = 1; final int widthRatio = Math.round((float)reqWidth / 100f); final int heigthRatio = Math.round((float) reqHeight / 100f); // 取最小值 這將保證壓縮出來的圖片大于或者等于請求的寬度或者高度 inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio; Log.w(TAG, "first inSampleSize = " + inSampleSize); final int totalPixel = 100 * 100; final int totalReqPixel = reqWidth * reqHeight * 2; Log.w(TAG, "totalReqPixel = " + totalReqPixel); while (totalPixel / (inSampleSize * inSampleSize) > totalReqPixel) { Log.w(TAG, "totalPixel = " + (totalPixel / (inSampleSize * inSampleSize))); inSampleSize ++; } Log.w(TAG, "LastInSampleSize = " + inSampleSize); optioins.inJustDecodeBounds = false; Bitmap lastBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_homepage, optioins); getBitmapDatas(lastBitmap); mImageView.setImageBitmap(lastBitmap); }
通過打印log我們可以清楚發(fā)現(xiàn)一張原始的圖片占有22317120字節(jié),經過壓縮后11158560(RGB_565)/ 22317120(RGB8888)明顯所占用的內存都減少了,盡量降低這種情況帶來的OOM。
做法:
1.optioins.inJustDecodeBounds = true設置為true可用于讀取該bitmap的寬高且不會占用內存。
2.optioins.inPreferredConfig = Bitmap.Config.RGB_565設置在內存中以占用最少的方式,相比RGB_8888只有其一半的內存占有。
3.final int widthRatio = Math.round((float)reqWidth / 100f);
final int heigthRatio = Math.round((float) reqHeight / 100f);
inSampleSize = widthRatio > heigthRatio ? heigthRatio : widthRatio;
計算壓縮比例,取最小值 這將保證壓縮出來的圖片大于或者等于請求的寬度或者高度。
4.在要顯示到ImageView的時候optioins.inJustDecodeBounds = false設回false這樣就能正常顯示了
// 計算bitmap所占內存值 public void getBitmapDatas(Bitmap bitmap) { Log.w(TAG, "Bitmap size = " + bitmap.getByteCount()); }
采用以上的壓縮方式 我們就能避免一張過大的圖片”浪費”的顯示在ImageView上造成內存消耗過大。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
分享名稱:AndroidBitmap壓縮方式分析
當前路徑:http://chinadenli.net/article36/piggsg.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供建站公司、電子商務、品牌網站建設、網站設計、網站內鏈、做網站
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)