Android_Gif播放(利用系統(tǒng)源碼)

前言

gif編碼詳細(xì)解析

注意: gif編碼格式有兩個(gè)版本,一個(gè)是87a一個(gè)是89a,分別是87年和89年制定的,本demo未兼容87a版本~

Android中g(shù)if播放一般是比較耗內(nèi)存的操作,Android中的ImageView不能直接播放gif(ios中是可以的),Android實(shí)現(xiàn)GIF播放的方式大致可分為兩種:①Java實(shí)現(xiàn) ②Jni實(shí)現(xiàn)
還有一些利用WebView等方式加載gif的方案~
使用Java方式實(shí)現(xiàn)的gif播放的是非常耗內(nèi)存的,就算是使用Glide這種優(yōu)秀的三方庫(kù),也是一樣的,所以項(xiàng)目中有g(shù)if播放需求,尤其是列表中有g(shù)if播放的,建議使用JNI的實(shí)現(xiàn)方式,github上有很多優(yōu)秀開源的相關(guān)項(xiàng)目,本文金座簡(jiǎn)單分析記錄!


Gif播放

本文主要簡(jiǎn)述利用系統(tǒng)源碼實(shí)現(xiàn)Gif播放的過程:
為什么是利用系統(tǒng)源碼呢?,因?yàn)锳ndroid系統(tǒng)也有播放gif動(dòng)畫的需求,比如開/關(guān)機(jī)動(dòng)畫,在Android源碼中的版本號(hào)\external\giflib,目錄下有具體實(shí)現(xiàn)gif播放的c代碼,這部分代碼基本上是不怎么有修改的,所以使用6.0版本,7.0版本,8.0版本...都沒多大區(qū)別,源碼可以自行度娘下載~

實(shí)現(xiàn)的邏輯流程大致如圖:


image.png

下面開始逐步實(shí)現(xiàn):

Copy系統(tǒng)源碼

簡(jiǎn)單粗暴,直接將系統(tǒng)\external\giflib目錄下的.c文件和.h頭文件copy到項(xiàng)目的cpp目錄下,這里我們只用到Gif的播放,所以只需要copy其中一部分就可以,不用所有的文件都copy進(jìn)來(lái),如圖:

Android源碼中的文件

然后修改對(duì)應(yīng)CmakeLists文件和項(xiàng)目的build.gradle文件

CMakeLists

cmake_minimum_required(VERSION 3.4.1)
add_library( # Sets the name of the library.
        native-lib
        SHARED
        src/main/cpp/native-lib.cpp
        src/main/cpp/dgif_lib.c
        src/main/cpp/gifalloc.c
        )

find_library(
        jnigraphics-lib
        jnigraphics )

find_library( # Sets the name of the path variable.
        log-lib
        log )
target_link_libraries(
        native-lib
        ${log-lib}
        ${jnigraphics-lib}
)

Java層

Java層的邏輯很簡(jiǎn)單,主要是使用一個(gè)Hanndler實(shí)現(xiàn)循環(huán)播放,和聲明調(diào)用一些JNI方法,大致如下:

MainActivity

public class MainActivity extends AppCompatActivity {
    private Bitmap bitmap;
    private ImageView imageView;
    private Button btn;
    private GifHandler gifHandler;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int interval = gifHandler.updateFream(bitmap);
            handler.sendEmptyMessageDelayed(1,interval);
            imageView.setImageBitmap(bitmap);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.image_view);
        btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ndkLoadGif();
            }
        });
    }

    public void ndkLoadGif() {
        File file = new File(Environment.getExternalStorageDirectory(), "demo.gif");
        gifHandler = new GifHandler(file.getAbsolutePath());
        int width = gifHandler.getWidth();
        int height = gifHandler.getHeight();
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //下一幀的刷新時(shí)間
        int interval = gifHandler.updateFream(bitmap);
        handler.sendEmptyMessageDelayed(1, interval);
    }

}

GifHandler

public class GifHandler {

    static {
        System.loadLibrary("native-lib");
    }

    //native 結(jié)構(gòu)體地址,方便傳參
    public long gifAddress;

    //加載gif的時(shí)候拿到結(jié)構(gòu)體地址
    public GifHandler(String path) {
        this.gifAddress = loadPath(path);
    }

    public int getWidth(){
        return getWidth(gifAddress);
    }

    public int getHeight(){
        return getHeight(gifAddress);
    }

    public int updateFream(Bitmap bitmap){
       return updateFrame(gifAddress,bitmap);
    }

    //通過路徑加載gif圖片(這里使用的是本地圖片,源碼中的gif加載是支持流的格式的)
    public native long loadPath(String path);
    //獲取gif的寬,long類型的ndkGif表示的是native 結(jié)構(gòu)體的地址
    public native int getWidth(long ndkGif);
    //獲取gif的高,long類型的ndkGif表示的是native 結(jié)構(gòu)體的地址
    public native int getHeight(long ndkGif);
    //每隔一段時(shí)間刷新一次,返回的int值表示下次刷新的時(shí)間間隔,long類型的ndkGif表示的是native 結(jié)構(gòu)體的地址
    public native int updateFrame(long ndkGif, Bitmap bitmap);
}

JNI層

JNI層主要是打開Gif文件,獲取gif寬高信息,遍歷Gif的每一幀,獲取延遲時(shí)間等,并且會(huì)將每一幀(Bitmap)返回給Java層用于刷新播放:

#include <jni.h>
#include <string>
#include <malloc.h>
#include <cstring>
#include "gif_lib.h"
#include <android/log.h>
#include <android/bitmap.h>
#define  LOG_TAG    "wangyi"
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define  argb(a,r,g,b) ( ((a) & 0xff) << 24 ) | ( ((b) & 0xff) << 16 ) | ( ((g) & 0xff) << 8 ) | ((r) & 0xff)

typedef struct GifBean{
    //當(dāng)前幀
    int currnt_frame;
    //總幀數(shù)
    int total_frame;
    //延遲時(shí)間數(shù)組,長(zhǎng)度不確定,根據(jù)gif幀數(shù)計(jì)算
    int *delays;
}GifBean;


//將gif的幀繪制到bitmap
void drawFrame(GifFileType *gifFileType, GifBean *gifBean, AndroidBitmapInfo bitmapInfo, void *pixels) {
    //獲取當(dāng)前幀
    SavedImage savedImage=gifFileType->SavedImages[gifBean->currnt_frame];
    //初始化指向圖片首地址
    int *px=(int *)pixels;
    int pointPixels;
    //Gif編碼中有邊界
    //遍歷的時(shí)候從邊界開始,不是從0開始
    GifImageDesc imageDesc=savedImage.ImageDesc;

    //字典,存放的是gif壓縮rgb數(shù)據(jù)
    ColorMapObject *colorMap=imageDesc.ColorMap;
    //部分圖片某些幀的ColorMapObject取到為null
    if(colorMap==NULL)
    {
        colorMap=gifFileType->SColorMap;
    }
    GifByteType gifByteType;//壓縮數(shù)據(jù)
    //指向第一行首地址
    px=(int *)((char *)px +bitmapInfo.stride * imageDesc.Top);
    //每一行的首地址
    int *line;
    for (int y = imageDesc.Top; y <imageDesc.Top+imageDesc.Height ; ++y) {
        line=px;
        for (int x = imageDesc.Left; x <imageDesc.Left+imageDesc.Width ; ++x) {
            //拿到位置坐標(biāo)的索引
            pointPixels=(y-imageDesc.Top)*imageDesc.Width+(x-imageDesc.Left);
            //gif中為了節(jié)省內(nèi)存rgb采用lzw壓縮,所以取rgb信息需要解壓
            gifByteType = savedImage.RasterBits[pointPixels];
            //拿到解壓后的rgb數(shù)據(jù)
            GifColorType gifColorType=colorMap->Colors[gifByteType];
            line[x] = argb(255,gifColorType.Red,gifColorType.Green,gifColorType.Blue);
        }
        //指向下一行首地址
        px=(int *)((char *)px +bitmapInfo.stride);
    }
}

extern "C"
JNIEXPORT jlong JNICALL
Java_com_jni_gifdemo_GifHandler_loadPath(JNIEnv *env, jobject instance, jstring path_) {
    const char *path = env->GetStringUTFChars(path_, 0);

    int err;
    GifFileType *gifFileType= DGifOpenFileName(path,&err);
     DGifSlurp(gifFileType);
    //malloc用于開辟內(nèi)存空間,可以理解為Java中的new一個(gè)對(duì)象,但是需要先清空內(nèi)存
    GifBean *gifBean=(GifBean *)malloc(sizeof(GifBean));
    //先清空內(nèi)存
    memset(gifBean,0, sizeof(GifBean));
    //綁定內(nèi)存地址,這里類似于Java中的View.setTag(new Object())
    //UserData; 的類型是void * 無(wú)符號(hào)類型,相當(dāng)于Java中的Object
    gifFileType->UserData=gifBean;

    //通過gif幀數(shù)計(jì)算延遲時(shí)間數(shù)組的長(zhǎng)度,清除空內(nèi)存
    gifBean->delays=(int *) malloc(sizeof(int)* gifFileType->ImageCount);
    //綁定內(nèi)存地址
    memset(gifBean->delays,0, sizeof(sizeof(int)* gifFileType->ImageCount));
    gifFileType->UserData=gifBean;
    //初始化當(dāng)前幀和總幀數(shù)
    gifBean->currnt_frame=0;
    gifBean->total_frame=gifFileType->ImageCount;

    ExtensionBlock *extensionBlock;
    //遍歷每一幀
    for (int i = 0; i <gifFileType->ImageCount ; ++i) {
        //遍歷每一幀中的擴(kuò)展塊(度娘Gif編碼)
        SavedImage frame= gifFileType->SavedImages[i];
        for (int j = 0; j <frame.ExtensionBlockCount ; ++j) {
            //取圖形控制擴(kuò)展塊,其中包含延遲時(shí)間
            if (frame.ExtensionBlocks[j].Function==GRAPHICS_EXT_FUNC_CODE){
                extensionBlock=&frame.ExtensionBlocks[j];
                break;
            }
        }

        //獲取延遲時(shí)間,extensionBlock的第二,三個(gè)元素一起存放延遲時(shí)間低8位和高8位向左偏移8位,進(jìn)行或運(yùn)算
        //乘10因?yàn)榫幋a的時(shí)間單位是1/100秒 乘10換算為毫秒
        if (extensionBlock){
            int frame_delay=10*(extensionBlock->Bytes[1]|(extensionBlock->Bytes[2]<<8));
            gifBean->delays[i]=frame_delay;
             LOGE("時(shí)間  %d   ",frame_delay);
        }
    }
    env->ReleaseStringUTFChars(path_,path);
    return (jlong)gifFileType;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_jni_gifdemo_GifHandler_getWidth(JNIEnv *env, jobject instance, jlong ndkGif) {
    GifFileType* gifFileType= (GifFileType*)ndkGif;
    return gifFileType->SWidth;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_jni_gifdemo_GifHandler_getHeight(JNIEnv *env, jobject instance, jlong ndkGif) {

    GifFileType* gifFileType= (GifFileType*)ndkGif;
    return gifFileType->SHeight;

}

extern "C"
JNIEXPORT jint JNICALL
Java_com_jni_gifdemo_GifHandler_updateFrame(JNIEnv *env, jobject instance, jlong ndkGif,
                                             jobject bitmap) {
    GifFileType* gifFileType= (GifFileType*)ndkGif;
    GifBean *gifBean= ( GifBean * )gifFileType->UserData;

    AndroidBitmapInfo bitmapInfo;
    AndroidBitmap_getInfo(env,bitmap,&bitmapInfo);

    //對(duì)bitmap加鎖,然后取緩沖區(qū)數(shù)據(jù)
    void *pixels;
    AndroidBitmap_lockPixels(env,bitmap,&pixels);

    drawFrame(gifFileType,gifBean,bitmapInfo,pixels);
    gifBean->currnt_frame+=1;
    if (gifBean->currnt_frame >= gifBean->total_frame-1){
        gifBean->currnt_frame=0;
          LOGE("重復(fù)播放  %d  ",gifBean->currnt_frame);
    }
    AndroidBitmap_unlockPixels(env,bitmap);
    //返回bitmap給java層
    return gifBean->delays[gifBean->currnt_frame];
}

完整代碼請(qǐng)見:Github

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末易遣,一起剝皮案震驚了整個(gè)濱河市犬绒,隨后出現(xiàn)的幾起案子避乏,更是在濱河造成了極大的恐慌幻枉,老刑警劉巖驻粟,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異务嫡,居然都是意外死亡货抄,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門蒲跨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)译断,“玉大人,你說我怎么就攤上這事或悲∷镞洌” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵巡语,是天一觀的道長(zhǎng)翎蹈。 經(jīng)常有香客問我,道長(zhǎng)男公,這世上最難降的妖魔是什么荤堪? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮枢赔,結(jié)果婚禮上澄阳,老公的妹妹穿的比我還像新娘。我一直安慰自己踏拜,他們只是感情好碎赢,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著速梗,像睡著了一般肮塞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上姻锁,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天枕赵,我揣著相機(jī)與錄音,去河邊找鬼位隶。 笑死烁设,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播装黑,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼弓熏!你這毒婦竟也來(lái)了恋谭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤挽鞠,失蹤者是張志新(化名)和其女友劉穎疚颊,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體信认,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡材义,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了嫁赏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片其掂。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖潦蝇,靈堂內(nèi)的尸體忽然破棺而出款熬,到底是詐尸還是另有隱情,我是刑警寧澤攘乒,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布贤牛,位于F島的核電站,受9級(jí)特大地震影響则酝,放射性物質(zhì)發(fā)生泄漏殉簸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一沽讹、第九天 我趴在偏房一處隱蔽的房頂上張望般卑。 院中可真熱鬧,春花似錦妥泉、人聲如沸椭微。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蝇率。三九已至,卻和暖如春刽沾,著一層夾襖步出監(jiān)牢的瞬間本慕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工侧漓, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留锅尘,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像藤违,于是被迫代替她去往敵國(guó)和親浪腐。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354