I am Hack Sparrow
Captain of the Internets.

Create animated JPG/JPEG using Node.js

How to create animated JPEGs

Can JPEGs be animated? Did you see an animated image on the Web and realized with great shock that it was a JPG/JPEG image? You see an animating JPEG right infront of your eyes and start question your knowledge that only the GIF format has the provision for animated images. How is that possible?

There are two scenarios to what could be happening.

  1. A GIF file got renamed to .jpg, but the browser is smart enough to detect the true soul of the image and starts to animate as it would animate a normal GIF, throwing the .jpg extension out of the window. If this is the case, the JPEG would not work on not-so-smart browsers like Internet Explorer though.
  2. The server is sending a Content-Type: 'image/gif' header for JPG/JPEG requests. This method is likely to get the pseudo-JPEGs animating across browsers, irrespective of how smart they are.

I will show you how to 'animate' JPEGs using Node.js using the Content-Type: 'image/gif' technique in Express.js. Make sure the corresponding .gif image exists for every .jpg request. Add the following code to your app.js. Restart the server and get ready to behold the magic of animating JPEGs, courtesy Node.js.

var fs = require('fs');
var util = require('util');
app.get('/:name.jpg', function(req, res) {
    res.header('Content-Type', 'image/gif');
    var anim_gif = './' +req.params.name + '.gif';
    util.pump(fs.createReadStream(anim_gif , {'bufferSize': 4 * 1024}), res);    

Yea, it's that simple. This technique can be implemented in any serverside language that allows you to send custom HTTP headers. All you have to do is send Content-Type: 'image/gif' and the proper GIF bitmap data, for .jpg requests.

As a Node.js developer, I hope you learnt not only how to 'animate' JPEGs, but also got to know more about routing in Express.js, HTTP headers, Streams, and util.pump().

2 Responses to “Create animated JPG/JPEG using Node.js”

  1. Jan Buschtöns says:

    I’m sorry, but where’s the sense? Why should I trick my users with misleading filenames?

  2. Captain says:

    I wrote this post as an explanation to the phenomena of animated JPEGs, not as a trick for your website. Someday someone might tell you they have seen animated JPEGs, now you can explain them how those work.

Make a Comment