许多解决方案都指向使用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的一个严肃插件,尽管我认为当它运行良好时,我们肯定可以修改它以供通用。
我感谢任何帮助!
感谢
我这样修改了您的代码:
# 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()
通过这种方式,您可以循环浏览文件,在中查找jpg文件/src/files/images/,然后直接在中编写调整大小的版本/out/images/with a modified name:在foo_resized.jpg中调整foo.jpg的大小。这样做不会"污染"src文件。
如果您只想用中调整大小的图像替换源图像/out/images/,您可以简单地为docpad.coffee
:中的后缀定义一个空字符串
plugins:
imagemagick:
suffix: ""
width: 300
或者只是在插件的配置对象中设置它!