Bitmap詳解

Bitmap的分析與使用

  • Bitmap的創(chuàng)建

    • 創(chuàng)建Bitmap的時候,Java不提供new Bitmap()的形式去創(chuàng)建,而是通過BitmapFactory中的靜態(tài)方法去創(chuàng)建,如:BitmapFactory.decodeStream(is);//通過InputStream去解析生成Bitmap(這里就不貼BitmapFactory中創(chuàng)建Bitmap的方法了,大家可以自己去看它的源碼),我們跟進(jìn)BitmapFactory中創(chuàng)建Bitmap的源碼,最終都可以追溯到這幾個native函數(shù)
        private static native Bitmap nativeDecodeStream(InputStream is, byte[] storage,
                    Rect padding, Options opts);
        private static native Bitmap nativeDecodeFileDescriptor(FileDescriptor fd,
                Rect padding, Options opts);
        private static native Bitmap nativeDecodeAsset(long nativeAsset, Rect padding, Options opts);
        private static native Bitmap nativeDecodeByteArray(byte[] data, int offset,
                int length, Options opts);
    

    Bitmap又是Java對象,這個Java對象又是從native,也就是C/C++中產(chǎn)生的,所以,在Android中Bitmap的內(nèi)存管理涉及到兩部分,一部分是native,另一部分是dalvik,也就是我們常說的java堆(如果對java堆與棧不了解的同學(xué)可以戳),到這里基本就已經(jīng)了解了創(chuàng)建Bitmap的一些內(nèi)存中的特性(大家可以使用adb shell dumpsys meminfo去查看Bitmap實例化之后的內(nèi)存使用情況)。

  • Bitmap的使用

    • 我們已經(jīng)知道了BitmapFactory是如何通過各種資源創(chuàng)建Bitmap了,那么我們?nèi)绾魏侠淼氖褂盟??以下是幾個我們使用Bitmap需要關(guān)注的點(diǎn)
      1. Size

        • 這里我們來算一下,在Android中,如果采用Config.ARGB_8888的參數(shù)去創(chuàng)建一個Bitmap,這是Google推薦的配置色彩參數(shù),也是Android4.4及以上版本默認(rèn)創(chuàng)建Bitmap的Config參數(shù)(Bitmap.Config.inPreferredConfig的默認(rèn)值),那么每一個像素將會占用4byte,如果一張手機(jī)照片的尺寸為1280×720,那么我們可以很容易的計算出這張圖片占用的內(nèi)存大小為 1280x720x4 = 3686400(byte) = 3.5M,一張未經(jīng)處理的照片就已經(jīng)3.5M了! 顯而易見,在開發(fā)當(dāng)中,這是我們最需要關(guān)注的問題,否則分分鐘OOM!
        • 那么,我們一般是如何處理Size這個重要的因素的呢?,當(dāng)然是調(diào)整Bitmap的大小到適合的程度啦!辛虧在BitmapFactory中,我們可以很方便的通過BitmapFactory.Options中的options.inSampleSize去設(shè)置Bitmap的壓縮比,官方給出的說法是

        If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory....For example, inSampleSize == 4 returns
        an image that is 1/4 the width/height of the original, and 1/16 the
        number of pixels. Any value <= 1 is treated the same as 1.

        很簡潔明了??!也就是說,只要按計算方法設(shè)置了這個參數(shù),就可以完成我們Bitmap的Size調(diào)整了。那么,應(yīng)該怎么調(diào)整姿勢才比較舒服呢?下面先介紹其中一種通過InputStream的方式去創(chuàng)建Bitmap的方法,上一段從Gallery中獲取照片并且將圖片Size調(diào)整到合適手機(jī)尺寸的代碼:

          static final int PICK_PICS = 9;
          
          public void startGallery(){
              Intent i = new Intent();
              i.setAction(Intent.ACTION_PICK);
              i.setType("image/*");
              startActivityForResult(i,PICK_PICS);
          }
          
           private int[] getScreenWithAndHeight(){
              WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
              DisplayMetrics dm = new DisplayMetrics();
              wm.getDefaultDisplay().getMetrics(dm);
              return new int[]{dm.widthPixels,dm.heightPixels};
          }
          
          /**
           *
           * @param actualWidth 圖片實際的寬度,也就是options.outWidth
           * @param actualHeight 圖片實際的高度,也就是options.outHeight
           * @param desiredWidth 你希望圖片壓縮成為的目的寬度
           * @param desiredHeight 你希望圖片壓縮成為的目的高度
           * @return
           */
          private int findBestSampleSize(int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) {
              double wr = (double) actualWidth / desiredWidth;
              double hr = (double) actualHeight / desiredHeight;
              double ratio = Math.min(wr, hr);
              float n = 1.0f;
              //這里我們?yōu)槭裁匆獙ふ?與ratio最接近的2的倍數(shù)呢?
              //原因就在于API中對于inSimpleSize的注釋:最終的inSimpleSize應(yīng)該為2的倍數(shù),我們應(yīng)該向上取與壓縮比最接近的2的倍數(shù)。
              while ((n * 2) <= ratio) {
                  n *= 2;
              }
      
              return (int) n;
          }
      
          @Override
          protected void onActivityResult(int requestCode, int resultCode, Intent data) {
              if(resultCode == RESULT_OK){
                  switch (requestCode){
                      case PICK_PICS:
                          Uri uri = data.getData();
                          InputStream is = null;
                          try {
                              is = getContentResolver().openInputStream(uri);
                          } catch (FileNotFoundException e) {
                              e.printStackTrace();
                          }
      
                          BitmapFactory.Options options = new BitmapFactory.Options();
                          //當(dāng)這個參數(shù)為true的時候,意味著你可以在解析時候不申請內(nèi)存的情況下去獲取Bitmap的寬和高
                          //這是調(diào)整Bitmap Size一個很重要的參數(shù)設(shè)置
                          options.inJustDecodeBounds = true;
                          BitmapFactory.decodeStream( is,null,options );
      
                          int realHeight = options.outHeight;
                          int realWidth = options.outWidth;
      
                          int screenWidth = getScreenWithAndHeight()[0];
                          
                          int simpleSize = findBestSampleSize(realWidth,realHeight,screenWidth,300);
                          options.inSampleSize = simpleSize;
                          //當(dāng)你希望得到Bitmap實例的時候,不要忘了將這個參數(shù)設(shè)置為false
                          options.inJustDecodeBounds = false;
      
                          try {
                              is = getContentResolver().openInputStream(uri);
                          } catch (FileNotFoundException e) {
                              e.printStackTrace();
                          }
      
                          Bitmap bitmap = BitmapFactory.decodeStream(is,null,options);
      
                          iv.setImageBitmap(bitmap);
      
                          try {
                              is.close();
                              is = null;
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
      
                          break;
                  }
              }
              super.onActivityResult(requestCode, resultCode, data);
          }
      

    我們來看看這段代碼的功效:
    壓縮前:

    壓縮前

    壓縮后:
    壓縮后

    對比條件為:1080P的魅族Note3拍攝的高清無碼照片

     2. **Reuse**
     上面介紹了``BitmapFactory``通過``InputStream``去創(chuàng)建`Bitmap`的這種方式,以及``BitmapFactory.Options.inSimpleSize`` 和 ``BitmapFactory.Options.inJustDecodeBounds``的使用方法,但將單個Bitmap加載到UI是簡單的,但是如果我們需要一次性加載大量的圖片,事情就會變得復(fù)雜起來。`Bitmap`是吃內(nèi)存大戶,我們不希望多次解析相同的`Bitmap`,也不希望可能不會用到的`Bitmap`一直存在于內(nèi)存中,所以,這個場景下,`Bitmap`的重用變得異常的重要。
     *在這里只介紹一種``BitmapFactory.Options.inBitmap``的重用方式,下一篇文章會介紹使用三級緩存來實現(xiàn)Bitmap的重用。*
     
           根據(jù)官方文檔[在Android 3.0 引進(jìn)了BitmapFactory.Options.inBitmap](https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inBitmap),如果這個值被設(shè)置了,decode方法會在加載內(nèi)容的時候去重用已經(jīng)存在的bitmap. 這意味著bitmap的內(nèi)存是被重新利用的,這樣可以提升性能, 并且減少了內(nèi)存的分配與回收。然而,使用inBitmap有一些限制。特別是在Android 4.4 之前,只支持同等大小的位圖。
         我們看來看看這個參數(shù)最基本的運(yùn)用方法。
         
         ```
         new BitmapFactory.Options options = new BitmapFactory.Options();
         //inBitmap只有當(dāng)inMutable為true的時候是可用的。
         options.inMutable = true;
         Bitmap reusedBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.reused_btimap,options);
         options.inBitmap = reusedBitmap;
         ```
         
           這樣,當(dāng)你在下一次decodeBitmap的時候,將設(shè)置了`options.inMutable=true`以及`options.inBitmap`的`Options`傳入,Android就會復(fù)用你的Bitmap了,具體實例:
         
         ```
         @Override
         protected void onCreate(@Nullable Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(reuseBitmap());
         }
    
         private LinearLayout reuseBitmap(){
             LinearLayout linearLayout = new LinearLayout(this);
             linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
             linearLayout.setOrientation(LinearLayout.VERTICAL);
     
             ImageView iv = new ImageView(this);
             iv.setLayoutParams(new ViewGroup.LayoutParams(500,300));
     
             options = new BitmapFactory.Options();
             options.inJustDecodeBounds = true;
             //inBitmap只有當(dāng)inMutable為true的時候是可用的。
             options.inMutable = true;
             BitmapFactory.decodeResource(getResources(),R.drawable.big_pic,options);
             
             //壓縮Bitmap到我們希望的尺寸
             //確保不會OOM
             options.inSampleSize = findBestSampleSize(options.outWidth,options.outHeight,500,300);
             options.inJustDecodeBounds = false;
     
             Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.big_pic,options);
             options.inBitmap = bitmap;
     
             iv.setImageBitmap(bitmap);
     
             linearLayout.addView(iv);
     
             ImageView iv1 = new ImageView(this);
             iv1.setLayoutParams(new ViewGroup.LayoutParams(500,300));
             iv1.setImageBitmap( BitmapFactory.decodeResource(getResources(),R.drawable.big_pic,options));
             linearLayout.addView(iv1);
     
             ImageView iv2 = new ImageView(this);
             iv2.setLayoutParams(new ViewGroup.LayoutParams(500,300));
             iv2.setImageBitmap( BitmapFactory.decodeResource(getResources(),R.drawable.big_pic,options));
             linearLayout.addView(iv2);
     
     
             return linearLayout;
         }
         ```
         
          以上代碼中,我們在解析了一次一張1080P分辨率的圖片,并且設(shè)置在`options.inBitmap`中,然后分別decode了同一張圖片,并且傳入了相同的`options`。最終只占用一份第一次解析`Bitmap`的內(nèi)存。
         
     3. **Recycle**
     一定要記得及時回收Bitmap,否則如上分析,你的native以及dalvik的內(nèi)存都會被一直占用著,最終導(dǎo)致OOM
     
     
     ```
     // 先判斷是否已經(jīng)回收
     if(bitmap != null && !bitmap.isRecycled()){
         // 回收并且置為null
         bitmap.recycle();
         bitmap = null;
     }
     System.gc();
     ```
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容