How to generate and serve images.

How to generate and serve images.

using javascript!

ยท

2 min read

In this post, I am gonna walk you through a small project that I build for fun as an example to better explain.

๐ŸŒˆ Introduction

I wanted to build an API that would give me a random quote as an image every time I make a GET request. Now I was making a personal notion dashboard for tracking my productivity and I thought it would be nice to see a new motivational quote every time I open notion.

โšก Install the required dependencies

If you are following through, do install these dependencies

  • express - required to serve the image
  • inspirational-quotes - this library provides with a random inspirational quote
  • text-to-image - helps convert the quote into an image
  • image-data-uri - format the image data

Run this to install all the dependencies

npm i express inspirational-quotes text-to-image image-data-uri

๐Ÿš€ Driver Code

const express = require('express');
const quote = require('inspirational-quotes');
const textToImage = require('text-to-image');
const ImageDataURI = require('image-data-uri');



const app = express();

app.get('/', async (req,res) => {
  try {
        res.setHeader("content-type", "image/png");
    res.setHeader("Cache-Control", "no-cache");
        const img = await textToImage.generate(quote.getRandomQuote(), {
            maxWidth: 800,
      fontSize: 28,
      fontWeight: 'bold',
      textAlign: 'center',
      textColor: '#11324D',
      margin: 40
        });

        return res.send(ImageDataURI.decode(img).dataBuffer);
    } catch (error) {
        return res.send(error);
    }
})

app.listen(process.env.PORT);

You can check the GitHub Repo ๐Ÿ“ฆ. Feel free to open an issue for any ideas or doubt.