节点ImageMagick调整大小不保留文件名

时间:2013-02-13 23:28:41

标签: node.js image-processing imagemagick docpad node-imagemagick

很多解决方案都指向使用mogrify,如果它是Node js实现的一部分,那将会很有效。我需要做的就是调整图像大小并保留文件名,但将它们放在一个单独的“已调整大小”文件夹中。这是我在这里做的(在coffeescript中,作为DocPad静态网站生成器的插件):

# 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"

结果是我的图像被正确调整大小并放在正确的文件夹中,但名称本身是“-0.jpg,-1.jpg,-2.jpg”,依此类推。我真的是为了我们自己的特定用途而写这个,而不是DocPad的一个严肃的插件,虽然我认为当它运行良好时我们肯定可以修改它以供一般使用。

我感谢任何帮助!

由于

1 个答案:

答案 0 :(得分:0)

我修改了你的代码:

# 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()

这样,你循环遍历在./src/files/images/中查找jpg文件的文件,然后直接在带有修改名称的./out/images/中编写调整大小的版本:foo.jpg调整大小foo_resized.jpg。通过这样做,您不会“污染”您的src文件。

如果您只想用./out/images/中已调整大小的源图像替换源图像,则可以在docpad.coffee中为后缀定义一个空字符串:

plugins:
  imagemagick:
    suffix: ""
    width: 300

或者只是在插件的配置对象中设置它!