1

I am working on some project where I need to have a lot of image files (preferably in jpg) format of predefined sizes (Not the height and width but file size in Kb/Mb).

So I might need to generate a random image of 100 KB in size and another random image of 2 MB in size.

How should I go about this using NodeJS?

I found this Random Image Generator code to generate a random image but it does not allow me to specify the file size.

All suggestions and wild guesses are welcome.

Gunjan Karun
  • 765
  • 1
  • 8
  • 18

2 Answers2

8

I don't speak node, but at the command line using ImageMagick, this will get you a large JPEG image:

convert -size 1000x2000 xc:gray +noise gaussian large.jpg

If you then use -define jpeg:extent=400kb on that you will get a 400kb file, +/- a little:

convert large.jpg -define jpeg:extent=400kb 400kb.jpg

Change the 400kb to suit your needs. If you want to do it all in one go, you can do this:

convert -size 1000x2000 xc:gray +noise gaussian jpg: | convert -define jpeg:extent=400kb - 400kb.jpg

In node, can you use the raw interface? It'll look something like

im.convert(['-size','1000x2000','xc:gray','+noise','gaussian','output.jpg'],
   function(...)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    I'll chime in, here is an answer I gave about using imagemagick from node https://stackoverflow.com/a/16106655/1380669 – Plato Jun 05 '15 at 17:52
1

You need to work out what dimensions and DPI will give you the file-size you want. Given that you don't seem to care too much about what the image looks like, let's pick 100 DPI pseudo-randomly.

An image that is x inches by y inches at 100 DPI will take up

(100*x)*(100*y)==fileSize

per colour channel. If you're looking for full colour, you'll need three of these, so

3*(100*x)*(100*y)==fileSize

Now you need to drop in your fileSize, pick a value for x or y, solve for the other value and generate an image of size x by y at 100 DPI to produce your required filesize.

Evan Knowles
  • 7,426
  • 2
  • 37
  • 71