node.jsimage-processingimagemagickdocpadnode-imagemagick

Node ImageMagick resize doesn't preserve file name


A lot of solutions are pointing toward's using mogrify, which would work great if it was part of the Node js implementation. All I need to do is resize my images and retain the file names, but place them in a separate "resized" folder. Here's what I'm doing here (in coffeescript, as a plugin for DocPad static website generator):

# Export Plugin
module.exports = (BasePlugin) ->

  im = require 'imagemagick'

  # Define Plugin
  class ImageMagickPlugin extends BasePlugin

      # Plugin name
      name: 'imagemagick'

      im.resize
        srcPath: './src/files/images/source/*.jpg'
        dstPath: "./src/files/images/resized/.jpg"
        width: 256
      , (err, stdout, stderr) ->
        throw err  if err
        console.log "resized some files to fit within 256"

The result is that my images are resized properly, and placed in the correct folder, but the names themselves are "-0.jpg, -1.jpg, -2.jpg", and so on. I'm really writing this for our own specific use, rather than a serious plugin for DocPad, though I think when it's working well we can definitely modify it for general use.

I appreciate any help!

Thanks


Solution

  • I modified your code like this :

    # Export Plugin
    module.exports = (BasePlugin) ->
    
      im = require('imagemagick')
    
      # Define Plugin
      class ImageMagickPlugin extends BasePlugin
        # Plugin name
          name: 'imagemagick'
          config:
            source: "images"
            suffix: "_resized"
            width: 256
    
          writeAfter: (opts,next) ->
            docpad = @docpad
            config = @config
            docpad.getDatabase().forEach (document) ->
              attr =  document.attributes
              if attr.extension is 'jpg' and attr.relativeDirPath is config.source
                srcPath = './src/files/' + attr.relativePath
                dstPath = './out/' + config.source + "/" + attr.basename + config.suffix + ".jpg"
                im.resize
                  srcPath: srcPath
                  dstPath: dstPath
                  width: config.width
                , (err, stdout, stderr) ->
                  throw err  if err
                  console.log "File resized: " + attr.filename
            next()
    

    This way, you loop over the files looking for jpg files in ./src/files/images/ and you write the resized version directly in the ./out/images/ with a modified name : foo.jpg is resized in foo_resized.jpg. By doing this, you don't "pollute" your src files.

    If you just want to replace the source images by the resized ones in ./out/images/, you can simply define an empty string for the suffix in docpad.coffee:

    plugins:
      imagemagick:
        suffix: ""
        width: 300
    

    or just set it in the config object of the plugin!