Search code examples
imagebase64pnggif

How to Convert an image in PNG format to GIF Format


I need to convert a PNG image Base 64 to GIF Base 64 format in JavaScript or C#.


Solution

  • If you can use ffmpeg with nodejs, you could spawn an ffmpeg process inside of node.js which will allow you to convert apng/animated-webp to an animated gif. Although this solution is not purely a node.js solution, it can be combined with node.js and used in any environment which node.js can function in.

    [Edit]

    According to the status of this ffmpeg ticket, you can not decode animated WEBP images with ffmpeg.

    Using ffmpeg you can convert apng files to .gif files.

    I have provided an example script which assumes that you have ffmpeg installed and configured in your PATH environment variable.

    The usage of this function is fairly simple. Just replace "/path/to/file" with where your file is located (i.e. "./input.apng") and it will output a file named: "input.apng.gif" in the same directory.

    var gifLocation = await convertToGif("/path/to/file")
    .catch((err) =>
    {
        console.error("[Error]", err);
    });
    
    if (gifLocation)
        console.log("Location:", gifLocation);
    

    Here's a working script (without the path to a file)

    const { exec } = require('child_process');
    const fs = require("fs");
    
    async function convertToGif(inputFile)
    {
        return new Promise(function(resolve, reject)
        {
            if (!fs.existsSync(inputFile))
            {
                console.error("[ffmpeg] File doesn't exist");
                reject(false);
                return;
            }
    
            const ls = exec(`ffmpeg -i "${inputFile}" -f gif "${inputFile}.gif"`, function (error, stdout, stderr)
            {
                if (error)
                {
                    console.log(error.stack);
                    console.log('[ffmpeg] Error code: '+error.code);
                    console.log('[ffmpeg] Signal received: '+error.signal);
                }
                /*console.log('[ffmpeg] Child Process STDOUT: '+stdout);
                console.log('[ffmpeg] Child Process STDERR: '+stderr);*/
            });
        
            ls.on('exit', function (code)
            {
                //console.log('[ffmpeg] Child process exited with exit code ' + code);
                if (code != 0)
                {
                    reject(false);
                }
                else
                {
                    resolve(`${inputFile}.gif`);
                }
            });
        });
    }
    
    async function run()
    {
        var gifLocation = await convertToGif("/path/to/file")
        .catch((err) =>
        {
            console.error("[Error]", err);
        });
    
        if (gifLocation)
            console.log("Location:", gifLocation);
    }
    
    run();