圖片框架 - Glide解碼webp動(dòng)圖淺析

接上篇,最終通過ByteBufferWebpDecoder執(zhí)行decode來對(duì)獲取的圖片數(shù)據(jù)進(jìn)行解碼。

項(xiàng)目是出自:https://github.com/zjupure/GlideWebpDecoder

ByteBufferWebpDecoder.java

@Override
public Resource<WebpDrawable> decode(@NonNull ByteBuffer source, int width, int height, @NonNull Options options) throws IOException {
    int length = source.remaining();
   byte[] data = new byte[length];
   source.get(data, 0, length);

    //1
   WebpImage webp = WebpImage.create(data);
   int sampleSize = Utils.getSampleSize(webp.getWidth(), webp.getHeight(), width, height);

    //2
   WebpDecoder webpDecoder = new WebpDecoder(mProvider, webp, source, sampleSize);
    webpDecoder.advance();

    //3
    Bitmap firstFrame = webpDecoder.getNextFrame();
   if (firstFrame == null) {
        return null;
   }

    Transformation<Bitmap> unitTransformation = UnitTransformation.get();
  
   //4
   return new WebpDrawableResource(new WebpDrawable(mContext, webpDecoder, mBitmapPool, unitTransformation, width, height,
           firstFrame));
}
1.WebpImage.create(data);

WebpImage.java

public static WebpImage create(byte[] source) {
    Preconditions.checkNotNull(source);
   ByteBuffer byteBuffer = ByteBuffer.allocateDirect(source.length);
   byteBuffer.put(source);
   byteBuffer.rewind();
   return nativeCreateFromDirectByteBuffer(byteBuffer);
}

這里native代碼基于google開源項(xiàng)目 https://github.com/webmproject/libwebp

web.cpp

/**
* Creates a new WebPImage from the specified byte buffer. The data from the byte buffer is copied
* into native memory managed by WebPImage.
*
* @param byteBuffer A java.nio.ByteBuffer. Must be direct. Assumes data is the entire capacity
*      of the buffer

* @return a newly allocated WebPImage
*/

jobject WebPImage_nativeCreateFromDirectByteBuffer(JNIEnv* pEnv, jclass clazz, jobject byteBuffer) {
    jbyte* bbufInput = (jbyte*) pEnv->GetDirectBufferAddress(byteBuffer);
   if (!bbufInput) {
        throwIllegalArgumentException(pEnv, "ByteBuffer must be direct");
       return 0;
   }
    jlong capacity = pEnv->GetDirectBufferCapacity(byteBuffer);
   if (pEnv->ExceptionCheck()) {
        return 0;
   }
    std::vector<uint8_t> vBuffer(bbufInput, bbufInput + capacity);
   return WebPImage_nativeCreateFromByteVector(pEnv, vBuffer);

/**
* Creates a new WebPImage from the specified buffer.
*
* @param vBuffer the vector containing the bytes
* @return a newly allocated WebPImage
*/
jobject WebPImage_nativeCreateFromByteVector(JNIEnv* pEnv, std::vector<uint8_t>& vBuffer) {
    std::unique_ptr<WebPImage> spNativeWebpImage(new WebPImage());
   if (!spNativeWebpImage) {
        throwOutOfMemoryError(pEnv, "Unable to allocate native context");
       return 0;
   }
    // WebPData is on the stack as its only used during the call to WebPDemux.
   WebPData webPData;
   webPData.bytes = vBuffer.data();
   webPData.size = vBuffer.size();
   // Create the WebPDemuxer
   auto spDemuxer = std::unique_ptr<WebPDemuxer, decltype(&WebPDemuxDelete)> {
            WebPDemux(&webPData),
           WebPDemuxDelete
    };
   if (!spDemuxer) {
        // We may want to consider first using functions that will return a useful error code
       // if it fails to parse.
       throwIllegalArgumentException(pEnv, "Failed to create demuxer");
       //FBLOGW("unable to get demuxer");
       return 0;
   }

    spNativeWebpImage->pixelWidth = WebPDemuxGetI(spDemuxer.get(), WEBP_FF_CANVAS_WIDTH);
   spNativeWebpImage->pixelHeight = WebPDemuxGetI(spDemuxer.get(), WEBP_FF_CANVAS_HEIGHT);
   spNativeWebpImage->numFrames = WebPDemuxGetI(spDemuxer.get(), WEBP_FF_FRAME_COUNT);
   spNativeWebpImage->loopCount = WebPDemuxGetI(spDemuxer.get(), WEBP_FF_LOOP_COUNT);
   spNativeWebpImage->backgroundColor = WebPDemuxGetI(spDemuxer.get(), WEBP_FF_BACKGROUND_COLOR);

   // Compute cached fields that require iterating the frames.
   jint durationMs = 0;
   std::vector<jint> frameDurationsMs;
   WebPIterator iter;

   if (WebPDemuxGetFrame(spDemuxer.get(), 1, &iter)) {
        do {
            durationMs += iter.duration;
           frameDurationsMs.push_back(iter.duration);
       } while (WebPDemuxNextFrame(&iter));
       WebPDemuxReleaseIterator(&iter);
   }

    spNativeWebpImage->durationMs = durationMs;
   spNativeWebpImage->frameDurationsMs = frameDurationsMs;
   jintArray frameDurationsArr = pEnv->NewIntArray(spNativeWebpImage->numFrames);
   pEnv->SetIntArrayRegion(frameDurationsArr, 0, spNativeWebpImage->numFrames, spNativeWebpImage->frameDurationsMs.data());

   // Ownership of pDemuxer and vBuffer is transferred to WebPDemuxerWrapper here.
   // Note, according to Rob Arnold, createNew assumes we throw exceptions but we don't. Though
   // he claims this won't happen in practice cause "Linux will overcommit pages, we should only
   // get this error if we run out of virtual address space." Also, Daniel C may be working
   // on converting to exceptions.

   spNativeWebpImage->spDemuxer = std::shared_ptr<WebPDemuxerWrapper>(
            new WebPDemuxerWrapper(std::move(spDemuxer), std::move(vBuffer)));
   // Create the WebPImage with the native context.
   jobject ret = pEnv->NewObject(
            sClazzWebPImage,
           sWebPImageConstructor,
           (jlong) spNativeWebpImage.get(),
           (jint)spNativeWebpImage->pixelWidth,
           (jint)spNativeWebpImage->pixelHeight,
           (jint)spNativeWebpImage->numFrames,
           (jint)spNativeWebpImage->durationMs,
           frameDurationsArr,
           (jint)spNativeWebpImage->loopCount,
           (jint)spNativeWebpImage->backgroundColor);

   if (ret != nullptr) {
        // Ownership was transferred.
       spNativeWebpImage->refCount = 1;
       spNativeWebpImage.release();
   }
    return ret;
}

這里就是在native創(chuàng)建WebpImage, 同時(shí)將byte buffer copy到native由WebpImage管理,同時(shí)native WebpImage 會(huì)創(chuàng)建一個(gè)java層的WebpImage供上層調(diào)用與之進(jìn)行JNI操作。所以真正處理webp圖片的功能在native WebpImage。

2.WebpDecoder初始化

WebpDecoder.java

private final LruCache<Integer, Bitmap> mFrameBitmapCache;
public WebpDecoder(GifDecoder.BitmapProvider provider, WebpImage webPImage, ByteBuffer rawData,
                  int sampleSize) {
    mBitmapProvider = provider;
   mWebPImage = webPImage;
...
    mTransparentFillPaint = new Paint();
...
   // 動(dòng)畫每一幀渲染后的Bitmap緩存
   mFrameBitmapCache = new LruCache<Integer, Bitmap>(MAX_FRAME_BITMAP_CACHE_SIZE) {
        @Override
       protected void entryRemoved(boolean evicted, Integer key, Bitmap oldValue, Bitmap newValue) {
            // Return the cached frame bitmap to the provider
           if (oldValue != null) {
                mBitmapProvider.release(oldValue);
           }
        }
    };
   setData(new GifHeader(), rawData, sampleSize);
}
3. webpDecoder.getNextFrame();
@Override
public Bitmap getNextFrame() {
    int frameNumber = getCurrentFrameIndex();
   ...
    for (int index = nextIndex; index < frameNumber; index++) {
        WebpFrameInfo frameInfo = mFrameInfos[index];
       if (!frameInfo.blendPreviousFrame) {
            disposeToBackground(canvas, frameInfo);
       }
        // render the previous frame
       renderFrame(index, canvas);
       if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "renderFrame, index=" + index + ", blend=" + frameInfo.blendPreviousFrame
                   + ", dispose=" + frameInfo.disposeBackgroundColor);
       }
        if (frameInfo.disposeBackgroundColor) {
            disposeToBackground(canvas, frameInfo);
       }
    }
    ...
    // Then put the rendered frame into the BitmapCache
   cacheFrameBitmap(frameNumber, bitmap);
   return bitmap;
}

private void renderFrame(int frameNumber, Canvas canvas) {
    WebpFrameInfo frameInfo = mFrameInfos[frameNumber];
   int frameWidth = frameInfo.width / sampleSize;
   int frameHeight = frameInfo.height / sampleSize;
   int xOffset = frameInfo.xOffset / sampleSize;
   int yOffset = frameInfo.yOffset / sampleSize;
   WebpFrame webpFrame = mWebPImage.getFrame(frameNumber);
   try {
        Bitmap frameBitmap = mBitmapProvider.obtain(frameWidth, frameHeight, mBitmapConfig);
       frameBitmap.eraseColor(Color.TRANSPARENT);
       webpFrame.renderFrame(frameWidth, frameHeight, frameBitmap);
       canvas.drawBitmap(frameBitmap, xOffset, yOffset, null);
       mBitmapProvider.release(frameBitmap);
   } finally {
        webpFrame.dispose();
   }
}

通過WebpFrame獲取幀數(shù)據(jù),然后進(jìn)行渲染,最后由mFrameBitmapCache緩存Bitmap。

4.最終return WebpDrawableResource

這里前面先初始化了一個(gè)unitTransformation,Transformation作用是:Resource經(jīng)過Transformation轉(zhuǎn)化為TransformedResource(eg:轉(zhuǎn)化為圓角或者圓形)。這里初始化的unitTransformation直接返回Resource,不做任何處理。

return new WebpDrawableResource(new WebpDrawable(mContext, webpDecoder, mBitmapPool, unitTransformation, width, height,  firstFrame));
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡(jiǎn)信或評(píng)論聯(lián)系作者。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,382評(píng)論 3 415
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,616評(píng)論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,112評(píng)論 1 323
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,355評(píng)論 0 288
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,869評(píng)論 1 334
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,727評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,928評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,165評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評(píng)論 1 282
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,585評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,892評(píng)論 2 372