Create Beautiful Background Changing Animated Gifs for Your Next Email Campaign

If a picture is worth a thousand words, an animated one must be worth even more. Nowadays, email marketers are pushing the boundaries of email design, by using animated GIFs to display their products and services in action.

Copy to clipboard
const cloudinary = require('cloudinary');
const async = require("async");

cloudinary.config({
    cloud_name: "<cloud_name>",
    api_key: "<api_key>",
    api_secret: "<api_secret>"
});

var baseImageUrl = "https://res.cloudinary.com/yakir/image/upload/v1578887770/r69yfic0g5ndp7vkv5rb.png";
var backgroundColors = ["#D9D9D9", "#F1E7DD", "#F7EABC", "#C7DCE8", "#FFFFFF"];
var delayBetweenFrames = 500;

createGif(baseImageUrl, backgroundColors, delayBetweenFrames, function (err, gifUrl) {
    if (err) {
        console.log(err)
    } else {
        console.log(gifUrl)
    }
})

function createGif(image_url, colors, delay, callback) {

   //1. Generate a unique tag for this uploading process.
    let tag = new Date().getTime();

    let imagesToUpload = [];
    for (var i = 0, len = colors.length; i < len; i++) {
        imagesToUpload.push({
            src: image_url,
            params: {
                tags: [tag],
                folder: 'tmp',
                background: colors[i]
            }
        });
    };

    var uploadTasks = [];
    imagesToUpload.map(function (element, index, items) {
        uploadTasks.push(function (callback) {
            console.log("Uploading image #" + index)
            cloudinary.v2.uploader.upload(element.src, element.params, function (err, result) {
                if (err) {
                    return callback(err)
                }
                callback(null, result);
            });
        });
    });

    //2. Uploading the base product image with different background-color
    async.parallelLimit(uploadTasks, 5, function (err) {
       //3. Call the `multi` method to generate gif with the tag
        console.log("Generating gif...")
        cloudinary.v2.uploader.multi(tag, {
            delay: delay
        }, function (error, gif) {
            if (error) {
                return callback(error)
            } else {
                //4. Delete the temporary images we used to generate the gif
                console.log("Deleting tmp images...")
                cloudinary.v2.api.delete_resources_by_tag(tag, {}, function (error, result) {
                    if (error) {
                        return callback(error)
                    } else {
                        console.log("Done! :)")
                        callback(null, gif.secure_url)
                    }
                });
            }
        });
    });
}
by Yakir Perlin