Glide4.8源碼拆解(四)Bitmap解析之"下采樣"淺析

前言

Glide歸根結底是一個圖片加載框架,它必定會涉及到BitmapFactory相關API把Bitmap讀取到內存;可能你們已經很熟悉如何高效的加載Bitmap(好比使用inSample等),這一章仍是要看一看Glide是如何玩轉的;html

本文主要分析這兩個類:java

  • DownsampleStrategy
  • Downsampler

從"Glide會對原圖進行放大"案例開始

假設咱們有一張寬高100x200的網絡圖片,須要加載到300x300像素的ImageView上(scaleType屬性爲CenterCrop),用Glide加載,不作任何處理會獲得多大的Bitmap?git

Glide.with(MainActivity.this).load(URL).listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
          return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
          if (resource instanceof BitmapDrawable){
            Bitmap bitmap = ((BitmapDrawable) resource).getBitmap();
            Log.d("onResourceReady",bitmap.toString());
          }
          return false;
        }
      }).into(vh.imageView);
複製代碼

不出意外會獲得300*300的Bitmap,Bitmap比例顯然被放大了;github

我懷疑是進行了Transformation操做,因此咱們要禁用Transformation;緩存

假設咱們對RequestOptions加上noTransformation的屬性,好比這個樣子:bash

RequestOptions requestOptions = RequestOptions.noTransformation();
 Glide.with(MainActivity.this).load(URL).apply(requestOptions).listener(xxx).into(vh.imageView);
複製代碼

不出意外會獲得300*600的Bitmap,Bitmap比例依然在被放大,甚至更大了;網絡

若是咱們不想讓Bitmap被放大,能夠用加載原圖尺寸的方式,好比設置override(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL)或者用SimpleTarget這樣的Target,可是加載原圖終究不是解決方案,爲何?內存的緣由,大部分狀況下咱們仍是但願Glide來對圖片進行縮小,加載原圖的操做等因而直接把APP往OOM送近了一步;app

Bitmap被放大不是Glide發明的,是Android官方帶的頭,好比同一張圖片,放在res中不一樣drawable文件夾下,獲得的尺寸不同;既然如此,Bitmap被放大確定是有積極意義的,也難怪Glide不多說起這事;框架

可是,總會有強迫症患者不想Bitmap被放大,Glide確定也想到了這一點,具體怎麼限制Bitmap不會放大,答案的使用RequestOptions.downsample()方法;ide

RequestOptions.downsample()方法接受參數類型爲:DownsampleStrategy,那麼咱們從DownsampleStrategy開始分析;

DownsampleStrategy

DownsampleStrategy顧名思義就是下采樣策略,下采樣是圖像進行縮小的一種方式;

DownsampleStrategy.java

public abstract class DownsampleStrategy {
//獲取縮放比例
public abstract float getScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth,
      int requestedHeight);
      
//獲取SampleSize策略
public abstract SampleSizeRounding getSampleSizeRounding(int sourceWidth, int sourceHeight,
      int requestedWidth, int requestedHeight);
}

public enum SampleSizeRounding {
    //內存優先 
    MEMORY,
    //圖片質量優先
    QUALITY,
  }
複製代碼

DownsampleStrategy是抽象類,提供兩個抽象方法,getScaleFactor()顧名思義是獲取縮放比例的,getSampleSizeRounding()多是獲取SampleSize的,DownsampleStrategy真是的實現類在其內部,幾個嵌套內部類FitCenter,CenterOutside,AtLeast,AtMost,None,CenterInside,除此以外,DownsampleStrategy還定義對應類的靜態變量;

DownsampleStrategy.java

public static final DownsampleStrategy FIT_CENTER = new FitCenter();

 public static final DownsampleStrategy CENTER_OUTSIDE = new CenterOutside();

 public static final DownsampleStrategy AT_LEAST = new AtLeast();
 
 public static final DownsampleStrategy AT_MOST = new AtMost();
 
 public static final DownsampleStrategy CENTER_INSIDE = new CenterInside();
 
 public static final DownsampleStrategy NONE = new None();
 
 public static final DownsampleStrategy DEFAULT = CENTER_OUTSIDE;
複製代碼

其中DEFAULT應該是Glide默認的策略,它指向的是CENTER_OUTSIDE,咱們簡單看一下CenterOutside的邏輯;

CenterOutside.java

private static class CenterOutside extends DownsampleStrategy {

    @Synthetic
    CenterOutside() { }

    @Override
    public float getScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth,
        int requestedHeight) {
        //寬度比例(控件/圖片)
      float widthPercentage = requestedWidth / (float) sourceWidth;
      //高度比例(控件/圖片)
      float heightPercentage = requestedHeight / (float) sourceHeight;
      //誰大取誰
      return Math.max(widthPercentage, heightPercentage);
    }

    @Override
    public SampleSizeRounding getSampleSizeRounding(int sourceWidth, int sourceHeight,
        int requestedWidth, int requestedHeight) {
      return SampleSizeRounding.QUALITY;
    }
  }
複製代碼

主要關注是CenterOutsidegetScaleFactor()邏輯,該邏輯很是簡單,主要是拿控件寬高/圖片寬高,獲得尺寸取最大值,咱們回到文章開頭的那個例子,假設此時控件寬高是300x300,圖片寬高100x200:

widthPercentage = 300/100 = 3.0f;

heightPercentage = 300/200 = 1.5f;

Math.max(widthPercentage, heightPercentage) = 3.0f;

從這個推理來看,文章開頭那個圖片確實會被放大3倍;

文章開頭試圖找控制縮放比例不超過1的,就是隻縮小不放大的,有沒有這樣的策略,實際上是有的,好比AtLeast,AtMost

AtLeast.java

private static class AtLeast extends DownsampleStrategy {

    @Synthetic
    AtLeast() { }

    @Override
    public float getScaleFactor(int sourceWidth, int sourceHeight, int requestedWidth,
        int requestedHeight) {
      int minIntegerFactor = Math.min(sourceHeight / requestedHeight, sourceWidth / requestedWidth);
      return minIntegerFactor == 0 ? 1f : 1f / Integer.highestOneBit(minIntegerFactor);
    }

    @Override
    public SampleSizeRounding getSampleSizeRounding(int sourceWidth, int sourceHeight,
        int requestedWidth, int requestedHeight) {
      return SampleSizeRounding.QUALITY;
    }
  }
複製代碼

AtLeastgetScaleFactor的邏輯簡要分析:

獲取圖片寬高/佈局寬高的比例的最小值,轉成int值;

若是這個值等於0,直接返回1,等於0其實就意味着圖片寬高/佈局寬高至少有一個是小於1的,也就屏蔽了須要放大的狀況;

若是minIntegerFactor不等一0,確定是須要縮小的,最後返回1f / Integer.highestOneBit(minIntegerFactor),其中Integer.highestOneBit(minIntegerFactor)是取minIntegerFactor的二進制形式最左邊的最高一位且高位後面所有補零,最後返回int型的結果;

其他的DownsampleStrategy實現類就不講解了,DownsampleStrategy是負責計算縮放比例和SampleSize策略,那麼真正去進行Bitmap計算的是Downsampler;

重頭戲Downsampler

Downsampler.java

Downsampler這個類在咱們以前分析Decode流程時已經遇到過它,該類的主要職責是從輸入流中解析出Bitmap,核心功能的入口方法在decode();

public Resource<Bitmap> decode(InputStream is, int requestedWidth, int requestedHeight,
      Options options, DecodeCallbacks callbacks) throws IOException {
    Preconditions.checkArgument(is.markSupported(), "You must provide an InputStream that supports"
        + " mark()");

    byte[] bytesForOptions = byteArrayPool.get(ArrayPool.STANDARD_BUFFER_SIZE_BYTES, byte[].class);
    //獲取默認的BitmapFactory
    BitmapFactory.Options bitmapFactoryOptions = getDefaultOptions();
    bitmapFactoryOptions.inTempStorage = bytesForOptions;
    //decodeFormat主要是RGB_8888||RGB_565
    DecodeFormat decodeFormat = options.get(DECODE_FORMAT);
    //獲取DownsampleStrategy
    DownsampleStrategy downsampleStrategy = options.get(DownsampleStrategy.OPTION);
    //是否fixedBitmapSize
    boolean fixBitmapToRequestedDimensions = options.get(FIX_BITMAP_SIZE_TO_REQUESTED_DIMENSIONS);
    //是否支持硬件位圖
    boolean isHardwareConfigAllowed =
      options.get(ALLOW_HARDWARE_CONFIG) != null && options.get(ALLOW_HARDWARE_CONFIG);

    try {
        //解析出Bitmap
      Bitmap result = decodeFromWrappedStreams(is, bitmapFactoryOptions,
          downsampleStrategy, decodeFormat, isHardwareConfigAllowed, requestedWidth,
          requestedHeight, fixBitmapToRequestedDimensions, callbacks);
     //BitmapResource包裝Bitmap
      return BitmapResource.obtain(result, bitmapPool);
    } finally {
      releaseOptions(bitmapFactoryOptions);
      byteArrayPool.put(bytesForOptions);
    }
  }
複製代碼

首先調用getDefaultOptions()獲取默認的BitmapFactory;

默認的BitmapFactory

默認的BitmapFactory使用一個隊列緩存,初始化設置在resetOptions()方法;

private static void resetOptions(BitmapFactory.Options decodeBitmapOptions) {
    decodeBitmapOptions.inTempStorage = null;
    decodeBitmapOptions.inDither = false;
    decodeBitmapOptions.inScaled = false;
    decodeBitmapOptions.inSampleSize = 1;
    decodeBitmapOptions.inPreferredConfig = null;
    decodeBitmapOptions.inJustDecodeBounds = false;
    decodeBitmapOptions.inDensity = 0;
    decodeBitmapOptions.inTargetDensity = 0;
    decodeBitmapOptions.outWidth = 0;
    decodeBitmapOptions.outHeight = 0;
    decodeBitmapOptions.outMimeType = null;
    decodeBitmapOptions.inBitmap = null;
    decodeBitmapOptions.inMutable = true;
  }
複製代碼

繼續decode()方法分析,首先從Option中獲取decodeFormatfixBitmapToRequestedDimensionsisHardwareConfigAllowed等,這個Option是從RequestOptions傳遞過來,表明用戶的配置;

  • decodeFormat表示解析格式,RGB_565或ARGB_8888;
  • fixBitmapToRequestedDimensions表示是否填充尺寸,不進行縮放
  • isHardwareConfigAllowed是否容許硬件位圖,詳細瞭解能夠看Glide官方文檔:muyangmin.github.io/glide-docs-…
  • BitmapResource包裝Bitmap返回; 真正的加載Bitmap邏輯在decodeFromWrappedStreams()方法:

decodeFromWrappedStreams

decodeFromWrappedStreams()

private Bitmap decodeFromWrappedStreams(InputStream is,
      BitmapFactory.Options options, DownsampleStrategy downsampleStrategy,
      DecodeFormat decodeFormat, boolean isHardwareConfigAllowed, int requestedWidth,
      int requestedHeight, boolean fixBitmapToRequestedDimensions,
      DecodeCallbacks callbacks) throws IOException {
    long startTime = LogTime.getLogTime();
    //解析出輸入流圖片尺寸
    int[] sourceDimensions = getDimensions(is, options, callbacks, bitmapPool);
    int sourceWidth = sourceDimensions[0];
    int sourceHeight = sourceDimensions[1];
    //獲得mimeType
    String sourceMimeType = options.outMimeType;
    if (sourceWidth == -1 || sourceHeight == -1) {
      isHardwareConfigAllowed = false;
    }
    //獲取圖片旋轉方向
    int orientation = ImageHeaderParserUtils.getOrientation(parsers, is, byteArrayPool);
    int degreesToRotate = TransformationUtils.getExifOrientationDegrees(orientation);
    boolean isExifOrientationRequired = TransformationUtils.isExifOrientationRequired(orientation);
    //判斷目標控件尺寸
    int targetWidth = requestedWidth == Target.SIZE_ORIGINAL ? sourceWidth : requestedWidth;
    int targetHeight = requestedHeight == Target.SIZE_ORIGINAL ? sourceHeight : requestedHeight;
    //獲取image類型
    ImageType imageType = ImageHeaderParserUtils.getType(parsers, is, byteArrayPool);
    //計算縮放
    calculateScaling();
    //計算其餘config
    calculateConfig();

    boolean isKitKatOrGreater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    //處理inBitmap
    if ((options.inSampleSize == 1 || isKitKatOrGreater) && shouldUsePool(imageType)) {
      int expectedWidth;
      int expectedHeight;
      if (sourceWidth >= 0 && sourceHeight >= 0
          && fixBitmapToRequestedDimensions && isKitKatOrGreater) {
        expectedWidth = targetWidth;
        expectedHeight = targetHeight;
      } else {
        float densityMultiplier = isScaling(options)
            ? (float) options.inTargetDensity / options.inDensity : 1f;
        int sampleSize = options.inSampleSize;
        int downsampledWidth = (int) Math.ceil(sourceWidth / (float) sampleSize);
        int downsampledHeight = (int) Math.ceil(sourceHeight / (float) sampleSize);
        expectedWidth = Math.round(downsampledWidth * densityMultiplier);
        expectedHeight = Math.round(downsampledHeight * densityMultiplier);
      }
      //設置inBitmap
      if (expectedWidth > 0 && expectedHeight > 0) {
        setInBitmap(options, bitmapPool, expectedWidth, expectedHeight);
      }
    }
    //BitmapFactory.Option配置完畢,調用decodeStream解析
    Bitmap downsampled = decodeStream(is, options, callbacks, bitmapPool);
    callbacks.onDecodeComplete(bitmapPool, downsampled);
    
    Bitmap rotated = null;
    if (downsampled != null) {
      //從新設置density
      downsampled.setDensity(displayMetrics.densityDpi);
      //處理旋轉信息
      rotated = TransformationUtils.rotateImageExif(bitmapPool, downsampled, orientation);
      if (!downsampled.equals(rotated)) {
      //添加進BitmapPool
        bitmapPool.put(downsampled);
      }
    }

    return rotated;
  }
複製代碼
  • decodeFromWrappedStreams()方法首先調用getDimensions()獲取輸入流圖片尺寸和mimeType
  • 獲取圖片的方向和旋轉角度;
  • 確認目標控件的寬高,獲取圖片的ImageType;
  • 調用calculateScaling()計算縮放信息;
  • 調用calculateConfig()計算其餘配置信息;
  • 根據配置,調用setInBitmap()設置inBitmap;
  • 上訴流程完成BitmapFactory.Option配置,調用decodeStream()解析輸入流;
  • 獲得Bitmap,對Bitmap作最後的操做;

getDimensions()

private static int[] getDimensions(InputStream is, BitmapFactory.Options options,
      DecodeCallbacks decodeCallbacks, BitmapPool bitmapPool) throws IOException {
    //只解析Bounds
    options.inJustDecodeBounds = true;
    decodeStream(is, options, decodeCallbacks, bitmapPool);
     //重置爲false;
    options.inJustDecodeBounds = false;
    return new int[] { options.outWidth, options.outHeight };
  }
複製代碼

getDimensions()使用options.inJustDecodeBounds = true讀取輸入流圖片信息;

計算縮放

calculateScaling()

private static void calculateScaling(
      ImageType imageType,
      InputStream is,
      DecodeCallbacks decodeCallbacks,
      BitmapPool bitmapPool,
      DownsampleStrategy downsampleStrategy,
      int degreesToRotate,
      int sourceWidth,
      int sourceHeight,
      int targetWidth,
      int targetHeight,
      BitmapFactory.Options options) throws IOException {
    //尺寸不能爲0
    if (sourceWidth <= 0 || sourceHeight <= 0) {
      return;
    }

    final float exactScaleFactor;
    //根據方向和角度獲取exactScaleFactor
    if (degreesToRotate == 90 || degreesToRotate == 270) {
      exactScaleFactor = downsampleStrategy.getScaleFactor(sourceHeight, sourceWidth,
          targetWidth, targetHeight);
    } else {
      exactScaleFactor =
          downsampleStrategy.getScaleFactor(sourceWidth, sourceHeight, targetWidth, targetHeight);
    }
    //exactScaleFactor不能小於等於0
    if (exactScaleFactor <= 0f) {
      throw new IllegalArgumentException("");
    }
    //獲取SampleSizeRounding
    SampleSizeRounding rounding = downsampleStrategy.getSampleSizeRounding(sourceWidth,
        sourceHeight, targetWidth, targetHeight);
    if (rounding == null) {
      throw new IllegalArgumentException("Cannot round with null rounding");
    }
    //獲取Bitmap輸出寬高
    int outWidth = round(exactScaleFactor * sourceWidth);
    int outHeight = round(exactScaleFactor * sourceHeight);
    //轉成int類型的factor
    int widthScaleFactor = sourceWidth / outWidth;
    int heightScaleFactor = sourceHeight / outHeight;
    //根據SampleSizeRounding獲得scaleFactor
    int scaleFactor = rounding == SampleSizeRounding.MEMORY
        ? Math.max(widthScaleFactor, heightScaleFactor)
        : Math.min(widthScaleFactor, heightScaleFactor);

    int powerOfTwoSampleSize;
    //不支持下采樣
    if (Build.VERSION.SDK_INT <= 23
        && NO_DOWNSAMPLE_PRE_N_MIME_TYPES.contains(options.outMimeType)) {
      powerOfTwoSampleSize = 1;
    } else {
    //在scaleFactor再進行處理,保證是2的指數冪
      powerOfTwoSampleSize = Math.max(1, Integer.highestOneBit(scaleFactor));
      if (rounding == SampleSizeRounding.MEMORY
          && powerOfTwoSampleSize < (1.f / exactScaleFactor)) {
        powerOfTwoSampleSize = powerOfTwoSampleSize << 1;
      }
    }
    //設置到inSampleSize
    options.inSampleSize = powerOfTwoSampleSize;
    int powerOfTwoWidth;
    int powerOfTwoHeight;
    //針對不一樣圖片格式,從新計算採樣後的寬高
    if (imageType == ImageType.JPEG) {
    //libjpeg引擎最大采樣size=8,skia會進行二次採樣
      int nativeScaling = Math.min(powerOfTwoSampleSize, 8);
      powerOfTwoWidth = (int) Math.ceil(sourceWidth / (float) nativeScaling);
      powerOfTwoHeight = (int) Math.ceil(sourceHeight / (float) nativeScaling);
      //如大大於8,skia會對剩下的進行二次採樣計算邏輯
      int secondaryScaling = powerOfTwoSampleSize / 8;
      if (secondaryScaling > 0) {
        powerOfTwoWidth = powerOfTwoWidth / secondaryScaling;
        powerOfTwoHeight = powerOfTwoHeight / secondaryScaling;
      }
    } else if (imageType == ImageType.PNG || imageType == ImageType.PNG_A) {
      powerOfTwoWidth = (int) Math.floor(sourceWidth / (float) powerOfTwoSampleSize);
      powerOfTwoHeight = (int) Math.floor(sourceHeight / (float) powerOfTwoSampleSize);
    } else if (imageType == ImageType.WEBP || imageType == ImageType.WEBP_A) {
    //不一樣版本採樣不一樣的計算方式round或者floor
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        powerOfTwoWidth = Math.round(sourceWidth / (float) powerOfTwoSampleSize);
        powerOfTwoHeight = Math.round(sourceHeight / (float) powerOfTwoSampleSize);
      } else {
        powerOfTwoWidth = (int) Math.floor(sourceWidth / (float) powerOfTwoSampleSize);
        powerOfTwoHeight = (int) Math.floor(sourceHeight / (float) powerOfTwoSampleSize);
      }
    } else if (
        sourceWidth % powerOfTwoSampleSize != 0 || sourceHeight % powerOfTwoSampleSize != 0) {
      int[] dimensions = getDimensions(is, options, decodeCallbacks, bitmapPool);
      powerOfTwoWidth = dimensions[0];
      powerOfTwoHeight = dimensions[1];
    } else {
      powerOfTwoWidth = sourceWidth / powerOfTwoSampleSize;
      powerOfTwoHeight = sourceHeight / powerOfTwoSampleSize;
    }
    //計算採樣後進行縮放的比例
    double adjustedScaleFactor = downsampleStrategy.getScaleFactor(
        powerOfTwoWidth, powerOfTwoHeight, targetWidth, targetHeight);
    //計算inTargetDensity和inDensity進行縮放
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    //這一塊計算方法沒有弄明白
      options.inTargetDensity = adjustTargetDensityForError(adjustedScaleFactor);
      options.inDensity = getDensityMultiplier(adjustedScaleFactor);
    }
    //設置inScaled
    if (isScaling(options)){
      options.inScaled = true;
    } else {
      options.inDensity = options.inTargetDensity = 0;
    }
  }
複製代碼

calculateScaling代碼看似複雜,可是仔細分析流程仍是很清晰的,該方法主要計算BitmapFactory.FactoryinSampleSizeinTargetDensityinDensityinSampleSize主要是進行向下採樣,採樣後天然會對圖片進行縮小,可是可能不知足目標縮放比例,因此再配合inTargetDensityinDensity進行二次縮放;主要針對兩個縮放變量powerOfTwoSampleSizeadjustedScaleFactor;具體流程分析:

流程一

  1. 計算powerOfTwoSampleSize過程:powerOfTwoSampleSize是最終賦值給options.inSampleSize的;
  • 根據圖片角度不一樣,分別調用downSampleStategy.getScaleFactor()方法,獲得exactScaleFactor;
  • 經過exactScaleFactor計算出outWidthoutHeight,再從新計算widthScaleFactorheightScaleFactor(ps:widthScaleFactor和heightScaleFactor是int類型,而exactScaleFactor是浮點型,結果是不同的);
  • 經過策略獲得int類型的比例scaleFactor
  • 判斷是否支持下采樣,計算出最終的縮放比例powerOfTwoSampleSize
  • 賦值給options.inSampleSize

流程二

  1. 計算adjustedScaleFactor過程:adjustedScaleFactor是最終計算options.inTargetDensityoptions.inDensity的;
  • 不一樣格式和版本的下采樣邏輯不一樣,Glide分別實現採樣邏輯的計算,而後生成採樣後的寬高尺寸powerOfTwoWidthpowerOfTwoHeight;
  • 再此調用downsampleStrategy.getScaleFactor()獲得縮放比adjustedScaleFactor;
  • 調用adjustTargetDensityForError()getDensityMultiplier()獲得inTargetDensityinDensity並賦值;
  • 上面inDensity依賴options.inScaled = true,最終還得判斷是否可以進行scale;

計算硬件位圖/Bitmap.Config

calculateConfig()

private void calculateConfig(
      InputStream is,
      DecodeFormat format,
      boolean isHardwareConfigAllowed,
      boolean isExifOrientationRequired,
      BitmapFactory.Options optionsWithScaling,
      int targetWidth,
      int targetHeight) {
      //若是支持硬件位圖
    if (hardwareConfigState.setHardwareConfigIfAllowed(
        targetWidth,
        targetHeight,
        optionsWithScaling,
        format,
        isHardwareConfigAllowed,
        isExifOrientationRequired)) {
      return;
    }
    //這種狀況,直接配置ARGB_8888
    if (format == DecodeFormat.PREFER_ARGB_8888
        || Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN) {
      optionsWithScaling.inPreferredConfig = Bitmap.Config.ARGB_8888;
      return;
    }
    //是否有透明的通道
    boolean hasAlpha = false;
    try {
      hasAlpha = ImageHeaderParserUtils.getType(parsers, is, byteArrayPool).hasAlpha();
    } catch (IOException e) {
    
    }
    //有透明的通道,須要配置成ARGB_8888
    optionsWithScaling.inPreferredConfig =
        hasAlpha ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
    if (optionsWithScaling.inPreferredConfig == Config.RGB_565) {
      optionsWithScaling.inDither = true;//565支持抖動界面
    }
  }
複製代碼

calculateConfig()主要是對BitmapFactory.Option的硬件位圖和inPreferredConfig進行計算;若是用戶配置8888直接配置,若是用戶配置565,還須要判斷是否有透明度通道,若是有透明度通道,依然採用8888解碼器;

硬件位圖

HardwareConfigState.java

boolean setHardwareConfigIfAllowed(
      int targetWidth,
      int targetHeight,
      BitmapFactory.Options optionsWithScaling,
      DecodeFormat decodeFormat,
      boolean isHardwareConfigAllowed,
      boolean isExifOrientationRequired) {
    if (!isHardwareConfigAllowed
        || Build.VERSION.SDK_INT < Build.VERSION_CODES.O
        || isExifOrientationRequired) {
        Android O以上支持
      return false;
    }
    //對尺寸有要求;
    boolean result =
        targetWidth >= MIN_HARDWARE_DIMENSION
            && targetHeight >= MIN_HARDWARE_DIMENSION
            && isFdSizeBelowHardwareLimit();

    if (result) {
      optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;
      optionsWithScaling.inMutable = false;
    }
    return result;
  }
複製代碼

硬件位圖Bitmap.Config.HARDWARE 是一種 Android O 添加的新的位圖格式。硬件位圖僅在顯存 (graphic memory) 裏存儲像素數據,並對圖片僅在屏幕上繪製的場景作了優化。

###設置InBitmap

setInBitmap()

private static void setInBitmap(
      BitmapFactory.Options options, BitmapPool bitmapPool, int width, int height) {
    @Nullable Bitmap.Config expectedConfig = null;
    // Avoid short circuiting, it appears to break on some devices.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    //硬件位圖不設置
      if (options.inPreferredConfig == Config.HARDWARE) {
        return;
      }
      //inJustDecodeBoudes時候有可能能夠獲取到
      expectedConfig = options.outConfig;
    }

    if (expectedConfig == null) {
      expectedConfig = options.inPreferredConfig;
    }
   
    options.inBitmap = bitmapPool.getDirty(width, height, expectedConfig);
  }
複製代碼

設置成硬件位圖的不能進行inBitmap操做,最終會設置options.inBitmap,其中緩存的位圖從bitmapPool中獲取;

解析輸出流

decodeStream()

萬事具體只差東風,設置完BitmapFactory.Options以後,正在解析輸入流的代碼就在decodeStream():

private static Bitmap decodeStream(InputStream is, BitmapFactory.Options options,
      DecodeCallbacks callbacks, BitmapPool bitmapPool) throws IOException {
    if (options.inJustDecodeBounds) {
      is.mark(MARK_POSITION);
    } else {
      callbacks.onObtainBounds();
    }
    int sourceWidth = options.outWidth;
    int sourceHeight = options.outHeight;
    String outMimeType = options.outMimeType;
    final Bitmap result;
    TransformationUtils.getBitmapDrawableLock().lock();
    try {
    //真正的解析調用
      result = BitmapFactory.decodeStream(is, null, options);
    } catch (IllegalArgumentException e) {
      if (options.inBitmap != null) {
        try {
        //發生異常要作inBitmap回收
          is.reset();
          bitmapPool.put(options.inBitmap);
          options.inBitmap = null;//不適用inBitmap
          return decodeStream(is, options, callbacks, bitmapPool);
        } catch (IOException resetException) {
          throw bitmapAssertionException;
        }
      }
      throw bitmapAssertionException;
    } finally {
      TransformationUtils.getBitmapDrawableLock().unlock();
    }
    if (options.inJustDecodeBounds) {
      is.reset();
    }
    return result;
  }
複製代碼

decodeStream()核心的方法是調用BitmapFactory.decodeStream(is, null, options)作解析工做,剩下的代碼都是對異常解析,若是發現異常時inBitmap不爲空,設置inBitmapnull並重試一次;

總結

本文主要是對Glide下采樣作了簡單介紹,從代碼流程上分析,能夠分爲對BitmapFactory.Options的配置、調用BitmapFactory解析輸入流以及對Bitmap最後的處理三個步驟,其中Options配置階段在計算縮放上最爲重要,其中在縮放因子計算階段,涉及native以及libjpeg底層的邏輯尤其重要,值得學習;

相關文章
相關標籤/搜索