基于FreeImage和gif.h将jpg转换为gif

2018-06-01  本文已影响49人  温暖春阳

本例将七张340*240的jpg图片转为gif
原文:http://yhhx.tech/2017/06/09/%E7%AC%94%E8%AE%B0/%E4%B8%A4%E4%B8%AAgif%E5%9B%BE%E7%89%87%E5%A4%84%E7%90%86%E5%BA%93%E4%BD%BF%E7%94%A8/

#include "gif.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <FreeImage.h>


int main()
{ 
    char        *outputFile = "x.gif";
    int32_t     gNum = 7;
    int32_t     gDelay = 40;
    int32_t     gWidth = 340;
    int32_t     gHeight = 240;
    uint8_t     **inputPics;
    inputPics = new uint8_t*[gNum];
    
    // 使用FreeImage库读取jpg原图数据
    FreeImage_Initialise(0);
    for (int n = 0; n < gNum; ++n)
    {
        char str[20];
        sprintf(str, "olr%d.jpg", n + 1);
    
        FIBITMAP *pfImg = FreeImage_Load(FIF_JPEG, str);
        if (pfImg)
        {
            gWidth = FreeImage_GetWidth(pfImg);
            gHeight = FreeImage_GetHeight(pfImg);
    
            // GetLine: 图像宽,字节
            // GetWidth: 图像宽,像素
            int byteStep = FreeImage_GetLine(pfImg) / FreeImage_GetWidth(pfImg);
    
            // save color to inputPics in RGB-format
            *(inputPics + n) = new uint8_t[gWidth * gHeight * 3];
            for (int i = 0; i < gHeight; ++i)
            {
                // !!!attention: FreeImage倒置了
                BYTE *bytes = FreeImage_GetScanLine(pfImg, i);
                int pos = 0;
                for (int j = 0; j < gWidth; ++j)
                {
                    pos = 3 * ((gHeight - i - 1)*gWidth + j);
                    *(*(inputPics + n) + pos + 0) = bytes[FI_RGBA_RED];
                    *(*(inputPics + n) + pos + 1) = bytes[FI_RGBA_GREEN];
                    *(*(inputPics + n) + pos + 2) = bytes[FI_RGBA_BLUE];
                    bytes += byteStep;
                }
            }
            FreeImage_Unload(pfImg);
        }
    }
    FreeImage_DeInitialise();
    
    GifWriter   gw;
    GifBegin(&gw,outputFile, gWidth, gHeight, gDelay);
    for (int n = 0; n < gNum; ++n)
    {
        // 写入gw的图片数据为rgba8888格式
        uint8_t *imgFrame = new uint8_t[4 * gWidth*gHeight];
        for (int k = 0; k < gWidth*gHeight; k++)
        {
            *(imgFrame + k*4 + 0) = *(*(inputPics + n) + k*3 + 0);
            *(imgFrame + k*4 + 1) = *(*(inputPics + n) + k*3 + 1);
            *(imgFrame + k*4 + 2) = *(*(inputPics + n) + k*3 + 2);
            //*(imgFrame + k * 4 + 3) = 0xff;
            // rgba中的a不起作用,赋不赋值不影响
        }
        GifWriteFrame(&gw, imgFrame, gWidth, gHeight, gDelay);
        delete imgFrame;
    }
    GifEnd(&gw);
}

编译脚本

g++ -g jpegtogif.c -I . -L /home/FreeImage3170/FreeImage -lfreeimage-3.17.0 -std=c++11
上一篇下一篇

猜你喜欢

热点阅读