问题描述
|
如何在带有Node.JS的ImageMagick中使用远程图像?
我想实现以下目标:
im.identify(\'http://www.website.com/image.jpg\',function(error,features) {
console.log(features);
});
解决方法
图像大小调整的快速代码段
http://nodejs.org/api/http.html
https://github.com/rsms/node-imagemagick
var thumb = \'\';
...
var request = http.get(options,function(response) {
var data = \'\';
response.setEncoding(\'binary\');
response.on(\'data\',function(chunk) {
data += chunk;
});
response.on(\'end\',function () {
im.resize({
srcData: data,width: 100,height: 75,format: \'jpg\'
},function(err,stdout,stderr) {
if (err) throw err;
thumb = stdout;
});
}
});
,这就是我使用远程图像的方式:
var srcUrl = \'http://domain.com/path/to/image.jpg\';
var http = srcUrl.charAt(4) == \'s\' ? require(\"https\") : require(\"http\");
var url = require(\"url\");
http.get(url.parse(srcUrl),function(res) {
if(res.statusCode !== 200) {
throw \'statusCode returned: \' + res.statusCode;
}
else {
var data = new Array;
var dataLen = 0;
res.on(\"data\",function (chunk) {
data.push(chunk);
dataLen += chunk.length;
});
res.on(\"end\",function () {
var buf = new Buffer(dataLen);
for(var i=0,len=data.length,pos=0; i<len; i++) {
data[i].copy(buf,pos);
pos += data[i].length;
}
im(buf).imFunctionYouWantToUse();
});
}
});
信用转到https://stuk.github.io/jszip/documentation/howto/read_zip.html,很难说我是否正确理解了您(考虑您在此处发布的信息量)。
使用imagemagick对远程图像执行操作的唯一方法是先将其下载到本地服务器。可以使用node.js的http.ClientRequest类完成此操作,之后,您应该能够使用Imagemagick像往常一样对图像进行操作。,这应该工作:
var request = require(\'request\');
var fs = require(\'fs\');
request({
\'url\': \'http://www.website.com/image.jpg\',\'encoding\':\'binary\'
},function (error,response,body) {
if (!error && response.statusCode == 200) {
fs.writeFileSync(\'/mylocalpath/image.jpg\',body,\'binary\');
im.identify(\'/mylocalpath/image.jpg\',function(error,features) {
console.log(features);
}
);
}else{
console.error(error,response);
}
}
)