Search code examples
javascriptnode.jsexpressgraphicsmagick

Output multiple files with GraphicsMagick


I have the following function set up which captures uploaded images, converts them and them writes them to the server. How do I go about renaming the converted file?

Currently the function takes the uploaded image and saves out one version of the image.

Goals:

  • Save out multiple versions of the uploaded image depending on image size.
  • Append filename with image size, eg. filename-400x400.jpg, filename-200x200.jpg

I'm not too sure how to go about the first one and the second, I think busboy is interfering with it, as filename in the function below includes to the extension. I need to be able to append the filename with the size before the extension. Can this be done with a regex?

Function:

// upload new user image
    app.post('/api/users/user/upload_image', function (req, res) {
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {

            console.log('\n\nUploading file: '.underline +filename .underline);
            console.log('Uploaded\nConverting...');
            var size = { width: 200, height: 200 };

            gm(file,'www/uploads/' + filename)
            .resize(size.width * 2, (size.height * 2) + '')
            .thumbnail(size.width, size.height + '^')
            .gravity('Center')
            .extent(size.width, size.height)
            .file(filename)
            .profile('*')
            .write('www/uploads/' + filename, function (err) {
                console.log("Success!".bold);
            });

        });

        req.busboy.on('finish', function () {
            res.writeHead(303, { Connection: 'close', Location: '/' });
            res.end();
        });
    });

Solution

  • As far as creating multiple files goes, you can just duplicate the gm chain you have already, just use a different filename.

    For the filename problem you could either just create your own filenames or use a regexp to insert the dimensions into the original filename. The latter you could use something like:

    // changes "foo.jpg" to "foo-400x400.jpg"
    filename.replace(/\.[^\.]+$/, '-400x400$&')