I recently had a need for some dummy images, a lot of dummy images, like ~150K images. The idea was simple, I’ve been working on an application that serves images through a custom UI. The images themselves contain highly-sensitive business data. I couldn’t have copies of the images available for development, that’s a big no-no, so I needed dummy images that would match the same image format and image name for development purposes. I also needed some unique identifying information in the body of the image to indicate that I was serving the appropriate dummy image.
Here’s the solution I came up with. I simply feed the image file name and some body text to the function and it spits out a simple .png image. Using Imagemagick installed on my development environment (Ubuntu in a Docker Container) I was able to leverage the power of Imagemagick with NodeJS to generate all of the images pretty quickly.
Getting Started
Install Imagemagick following the instructions for your environment.
Then in our project we need the imagemagick NPM module installed. The module is simply a wrapper around the imagemagick package installed at the OS level.
In our app.js we need a single function, generateImage() that accepts a single object with parameters like the file name, body text, etc. We’ll use the function to generate an image. Here we’re using the convert
method from Imagemagick to ‘convert’ an image generated on a the Imagemagick canvas to a more portable image format like .jpg.
app.js
const imagemagick = require('imagemagick');
const generateImage = (options) => {
const args = [
"-density", `${options.resolution * options.sampling_factor}`,
"-size", `${options.size * options.sampling_factor}x${options.size * options.sampling_factor}`,
`canvas:${options.background_color}`,
"-fill", options.text_color,
"-pointsize", `${options.point_size}`,
"-gravity", `${options.gravity}`,
"-annotate", "+0+0",
`${options.text_to_display}`,
"-resample", `${options.resolution}`,
`${options.file_location}/${options.file_name}.${options.file_extension}`
];
imagemagick.convert(args, (err, data) => {
if (err) {
console.log(`ERROR: ${err}`);
throw err;
} else {
console.log('Image complete');
}
});
}
const options = {
background_color: "#003366",
file_extension: 'jpg',
file_location: 'images',
file_name: 'test-image',
gravity: 'center',
height: 100,
point_size: 30,
resolution: 72,
size: 512,
sampling_factor: 3,
text_color: "#FFFFFF",
text_to_display: 'This is a test image',
width: 500
}
// Call the generate image function
generateImage(options);
The result is a simple image like this:
This simple example can be easily expanded to serve all kinds of use cases.