2014-02-06 75 views
27

我一直在尝试使用NodeJS的gm包创建一些缩略图,但我很幸运。我需要调整大于600x600的图片大小(可以是任意宽度/高度,从给定的宽度/高度开始),但是当我将大小传递给gm时,它会创建与我请求的大小不同的图片。调整大小和裁剪图像并保持纵横比NodeJS&gm

例如,给这个代码,我假设运行node app /path/to/image.png我会用黑白200x100尺寸接收图像,而是我,说,的180x100或者200x90图像...

gm(fileLocation) 
    .thumb(200, 100, 'processed.' + process.argv[2].split('.').pop(), function() { 
     console.log("Done!"); 
    }); 

我也尝试了调整大小选项。甚至还有一个选项,以迫使大小,但输出的宽高比去可怕......

gm('/path/to/image.jpg') 
    .resize(353, 257) 
    .write(writeStream, function (err) { 
     if (!err) console.log(' hooray! '); 
    }); 

回答

7

imagemagick包食用量的NodeJS:https://github.com/yourdeveloper/node-imagemagick

im.crop({ 
    srcPath: process.argv[2], 
    dstPath: 'cropped.' + process.argv[2].split('.').pop(), 
    width: 200, 
    height: 200, 
    quality: 1, 
    gravity: 'Center' 
}, function(err, stdout, stderr){ 
    if (err) throw err; 
    console.log('resized ' + process.argv[2].split('/').pop() + ' to fit within 200x200px'); 
}); 

更新:请注意,node-imagemagick包尚未更新很长一段时间。请考虑Freyday's answer,因为它是最新的。

-2

两件事情......

1)https://github.com/rsms/node-imagemagick - 这个包是不再支持我会建议你使用原包装。

2)它没有调整大小的原因是.resize函数需要一个字符串,而不是一个整数。它应该是... (“353”,“257”)

gm('/path/to/image.jpg') 
    .resize('353', '257') 
    .write(writeStream, function (err) { 
     if (!err) console.log(' hooray! '); 
    }); 
+3

'.resize'可以很好地处理数字。 –

99

要实现调整大小,裁剪图像和与gm模块重心,你可以使用类似这样:

gm('/path/to/image.jpg') 
    .resize('200', '200', '^') 
    .gravity('Center') 
    .crop('200', '200') 
    .write(writeStream, function (err) { 
    if (!err) console.log(' hooray! '); 
    }); 

'^'参数上resize功能会告诉GraphicsMagick工具使用的高度和宽度为最低而不是默认的行为,最大。生成的已调整大小的图像的宽度将为高度为您指定的尺寸,而不合格尺寸大于指定的尺寸。

然后gravity函数告诉GraphicsMagick函数应该如何工作,这会将图像裁剪为最终尺寸。

您可以找到由gm模块这里使用的GraphicsMagick工具选项的详细资料:http://www.graphicsmagick.org/GraphicsMagick.html

+13

这应该是被接受的答案,真的 – marksyzm

1

(由ImageMagick的除外),无需外部库的另一个解决方案是创建自己的解决方案:

var exec = require('child_process').exec; 

resize = function (image) { 
    var cmd = 'convert ' + image.src + 
    ' -resize ' + image.width + 'x' + image.height + '^' + 
    ' -gravity center -crop ' + image.width + 'x' + image.height + '+0+0 ' + 
    image.dst; 

    exec(cmd, function(error, stdout, stderr) { 
    if(error) { 
     console.log(error); 
    } 
    }); 
} 

然后称它为:

resize({ 
    src: sourceFile, 
    dst: destinyFile, 
    width: 320, 
    height: 240 
}); 

它将允许您的自定义质量参数,作物,水印等...

相关问题