Bannerbear Beginner Guide: How to Start Generating Images Dynamically in JavaScript with Bannerbear

If you want to integrate dynamic image generation into your JavaScript project, this article is for you! Learn how to do it effortlessly with Bannerbear—we’ll walk you through the entire process, from setup and implementation to achieving the final result.
by Josephine Loo ·

Contents

    In 2024, capturing user attention is more challenging than ever, with studies showing that the average user’s attention span has shrunk to just a few seconds. Eye-catching images become essential for grabbing user attention, yet creating them consistently can be a daunting task. This is where dynamic image generation comes into play.

    Dynamic image generation is the process of automatically creating customized images based on data or user input. It allows you to streamline and automate the creation of visually appealing content at scale. As a developer, you can easily integrate this capability into your application using Bannerbear’s API or Node.js library.

    In this article, we'll explore how to use Bannerbear, a powerful tool for dynamic image generation, to create eye-catching images automatically using JavaScript. We’ll guide you through the setup of Bannerbear, demonstrate how to use its Node.js library, and guide you in generating your first image. By the end of this guide, you will have the skills necessary to incorporate dynamic image generation into your JavaScript projects!

    Why Generate Images Dynamically: Use Cases

    Dynamic image generation simplifies and accelerates the creation of visual content. It helps save time, ensures consistency, and makes it easy to personalize content for different needs at any scale. Here are some examples where dynamic image generation can be particularly useful:

    • Social media content - Social media platforms demand a continuous stream of visually appealing posts, which can be time-consuming and labor-intensive to create manually. Dynamic image generation automates this by pulling data from websites, databases, or other external sources to generate images, saving designers time and effort in creating social media content.
    • E-commerce images - Dynamic image generation enables the automatic creation of website banners and product images that reflect the current pricing, discounts, and, promotions. This is especially useful during seasonal sales like Black Friday and Cyber Monday where a large volume of promotional images needs to be created for various products and discounts.
    • Events materials - For event organizers or event management platforms, dynamic image generation simplifies the creation of materials such as tickets, banners, and schedules. It can incorporate unique attendee information, QR codes, and URLs to create these items at scale automatically.
    • Link preview - Custom link preview images that showcase key information from the linked content—like titles, descriptions, and relevant graphics can significantly boost click-through rates on social media posts, email marketing campaigns, and messaging platforms. Dynamic image generation automates this process, eliminating the need for manual design for each link.

    🐻 Bear Tips: When sharing links on the internet, each platform has its own name for the preview that shows up. Common names include Open Graph images, X/Twitter Cards, Unfurled links (on Slack), and link cards.

    These examples demonstrate the benefits of dynamic image generation brings across various industries and applications, and Bannerbear offers a powerful solution to implement this.

    What is Bannerbear

    Bannerbear is a versatile tool that allows you to automatically generate custom images, videos, and more using external data. It offers APIs and libraries in various popular programming languages, including Nodes.js, Ruby, and PHP to make automating and integrating dynamic image generation into your projects easy.

    At its core, Bannerbear works with design templates that serve as blueprints for creating images. The design template can include two types of objects:

    • Static objects - Elements that remain constant in every generated image, such as a company logo.
    • Dynamic objects - Elements that change based on your provided data, such as text or images.

    Here’s an example of a Bannerbear design template:

    Bannerbear design template example - travel review template.png

    The template automatically generates the images below when different data is passed through its API or library :

    Bannerbear design template - travel review template result 1.png Bannerbear design template - travel review template result 2.png

    Getting Started with Bannerbear

    Now, let's walk through the process of setting up Bannerbear and using its Node.js library to generate images dynamically.

    Step 1. Set Up a Bannerbear Template

    To begin using Bannerbear, you'll need to create an account. After logging into the dashboard, set up a project and create a template within that project. This will give you a blank canvas where you can add layers of static and dynamic text, images, and other objects.

    Alternatively, you can duplicate any template from the Template Library, including the one below, and customize it to meet your needs:

    Bannerbear design template example - travel review template.png

    In the template above, we have the following modifiable dynamic objects:

    • Text - review, name, location
    • Image - background, avatar
    • Special object - star_rating

    Each object has a unique name that you can use in your code to modify it later on the template. We'll go into more detail on this in the following section.

    Step 2. Retrieve Your Project API Key and Template ID

    To access your Bannerbear project and the design template in your code, you need your project API key and template ID for authentication.

    On your template’s main page, you should see “Settings/API Key” in the top right corner. Click on it to reveal your API key:

    Bannerbear design template- travel review template - API key.png

    For the template ID, it can be found in the template option as shown in the screenshot below:

    Bannerbear design template- travel review template - template ID.png

    🐻 Bear Tips: Make sure to save the API key and template ID for use in your code later.

    Step 3. Set Up a Node.js Project

    Now that you have a Bannerbear account and template, let's set up a Node.js project. If you already have an existing project, skip to Step 4.

    Create a new directory for your project and navigate to it in the command prompt/terminal. Then, run the command below in the command prompt/terminal to initialize a new Node.js project:

    npm init
    

    After the project is initialized, create a new JavaScript file named index.js in the same directory:

    touch index.js
    

    Step 4. Install and Import the Bannerbear Library

    Run the command below in the command prompt/terminal to install the Bannerbear library:

    npm install bannerbear
    

    Next, import the library by adding the line below to your index.js file:

    const { Bannerbear } = require('bannerbear')
    

    Step 5. Generate Dynamic Images Using Bannerbear

    Let's write a simple script to generate an image using the template we discussed earlier. We'll create a Bannerbear client, use its create_image() method to generate a new image, and print the image URL to the console.

    In index.js, set up a self-invoking function and initialize an instance of the Bannerbear client with your project API key:

    (async () => {
      // Replace with your actual API key
      const bb = new Bannerbear('YOUR_API_KEY');
    })();
    

    Next, call the create_image() method, providing your template ID and a literal object that includes a modifications array and a true flag (which returns the image synchronously in the result). Then, log the image URL to the console:

    (async () => {
    	...
      // Replace with your actual template ID
      const images = await bb.create_image('YOUR_TEMPLATE_ID', {
        modifications: [
            {
              name: 'review',
              text: 'Fantastic restaurant with a good range of food on their menus. Brilliant service from very friendly staff. Would definitely return!',
            },
            {
              name: 'name',
              text: 'Nadia Alwi',
              background: '#2CB45B',
            },
            {
              name: 'location',
              text: 'Me. Healthy Food',
              color: '#2CB45B',
            },
            {
              name: 'avatar',
              image_url: 'https://images.pexels.com/photos/6832641/pexels-photo-6832641.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2',
            },
            {
              name: 'background',
              image_url: 'https://images.pexels.com/photos/4099237/pexels-photo-4099237.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2',
            },
            {
              name: 'star_rating',
              rating: 100,
            },
        ],
      }, true);
    
      console.log(images.image_url);
      
    })();
    

    The modifications array holds the key-value pairs for the dynamic object you want to change in the template. We’ll break down these key-value pairs in the following section.

    Step 6. Run the Script

    To generate an image, execute the script by running the command below:

    node index.js
    

    If the task is successful, the URL of the generated image will be displayed in the console:

    result of Bannerbear template dynamic image generation.png

    Alternatively, you can view the result directly on your Bannerbear dashboard by navigating to the main page of your template:

    result of Bannerbear template dynamic image generation in the dashboard.png

    Template Modifications Explained

    Now that you have a clear understanding of the image generation process, let’s take a closer look at the key-value pairs for the different objects included in the modifications array. Here’s a detailed breakdown:

    Text

    Three text objects are being modified:

    • The review object contains a text string providing a customer’s feedback.
    • The name object shows the name of the reviewer, with its background set to light green (#2CB45B).
    • The location object includes the name of the restaurant, and its text color is also changed to light green to match the theme.

      modifications: [ { name: 'review', text: 'Fantastic restaurant with a good range of food on their menus. Brilliant service from very friendly staff. Would definitely return!', }, { name: 'name', text: 'Nadia Alwi', background: '#2CB45B', }, { name: 'location', text: 'Me. Healthy Food', color: '#2CB45B', } ]

    Bannerbear design template - travel review template text object change.png

    Image

    You can easily change images within the template by specifying the name of the image object and providing the URL for the new image:

    • The avatar object lets you change the profile picture of the reviewer.
    • The background object lets you set a new background image for the template.

      modifications: [ { name: 'avatar', image_url: 'https://images.pexels.com/photos/6832641/pexels-photo-6832641.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2', }, { name: 'background', image_url: 'https://images.pexels.com/photos/4099237/pexels-photo-4099237.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2', } ]

    Bannerbear design template - travel review template image object change.png

    🐻 Bear Tips: Bannerbear detects faces and clearly defined subjects (smart crop) in images automatically. You can disable them from the template or code.

    Special Object (Star Rating)

    The star rating system has a maximum of five stars. It accepts a value between 0 and 100, and then converts it to a corresponding value within the 0-5 range:

    modifications: [
            {
              name: 'star_rating',
              rating: 100,
            }
    ]
    

    Bannerbear design template - travel review template star object change.png

    🐻 Bear Tips: There are other specialized objects available, including bar and line charts , as well as QR codes and bar codes.

    What's Next

    Congratulations! You’ve successfully learned how to set up a Bannerbear template and use its Node.js library to generate images. Now, whether you’re building a social media tool, an e-commerce platform, or any application that needs custom images, you can integrate dynamic image generation into your project just as you did in this tutorial!

    As you become more comfortable with the basics, you can explore several advanced features that Bannerbear offers:

    • Image collections - Generate images from multiple templates using the same data payload in a single API call.
    • Webhooks - Receive notifications when your image generation is complete.
    • Simple and Signed URLs - Create dynamic images on-demand through URL parameters.
    • Video Generation - Create dynamic videos using similar principles to image generation.

    For detailed instructions on how to use these features, be sure to refer to the official Bannerbear documentation. Sign up and start creating today!

    About the authorJosephine Loo
    Josephine is an automation enthusiast. She loves automating stuff and helping people to increase productivity with automation.

    How to Generate Wedding Invites for Your Entire Guest List

    Wedding invites set the tone for the event, but they don't need to be created one by one. In this article, you'll learn three easy ways to streamline the process with Bannerbear.

    How to Instantly Create and Send Pet Adoption Certificates by Email (Free Template!)

    Pet shelters and rescues often have limited means, so automating adoption certificate creation can reduce the load on staff and free up resources for other tasks. Here's how to set up a simple nocode automation that generates and sends certificates out in one go!

    How to Automatically Create Multi-Time Zone Event Posters with Node.js and Bannerbear

    Hosting online events, workshops, or webinars for a global audience? Use Bannerbear in Node.js to automatically generate event posters with the correct time zones for different regions!

    Automate & Scale
    Your Marketing

    Bannerbear helps you auto-generate social media visuals, banners and more with our API and nocode integrations

    Bannerbear Beginner Guide: How to Start Generating Images Dynamically in JavaScript with Bannerbear
    Bannerbear Beginner Guide: How to Start Generating Images Dynamically in JavaScript with Bannerbear