使用node-canvas操纵远程图像时出错:“给定的图像尚未完成加载”

时间:2012-06-22 20:31:18

标签: node.js canvas cairo

我正在尝试使用node-canvas来操作存储在远程服务器上的图像。我开始使用image-src示例并修改它,但我无法让它工作。这是我的代码:

var fs = require('fs'),
    http = require('http'),
url = require('url'),
canvas = require('./node-canvas/lib/canvas');

var outCanvas = new canvas(1000, 750);
var ctx = outCanvas.getContext('2d');

http.get(
    {
        host: 'farm8.staticflickr.com',
        port: 80,
        path: '/7108/7038906747_69a526f070_z.jpg'
    },
    function(res) {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk;
        });
        res.on('end', function () {
            img = new canvas.Image;
            img.src = data;
            ctx.drawImage(img, 0, 0, img.width, img.height);

            var out = fs.createWriteStream(__dirname + '/my-out.png')
                , stream = outCanvas.createPNGStream();

            stream.on('data', function(chunk){
                out.write(chunk);
            });
        });
    }
);

......这是我得到的错误:

/Users/daf/Documents/lolstagram/lolstagram-c.js:23
    ctx.drawImage(img, 0, 0, img.width, img.height);
       ^
Error: Image given has not completed loading
    at IncomingMessage.<anonymous> (/Users/daf/Documents/lolstagram/lolstagram-c.js:23:8)
    at IncomingMessage.emit (events.js:88:20)
    at HTTPParser.onMessageComplete (http.js:137:23)
    at Socket.ondata (http.js:1150:24)
    at TCP.onread (net.js:374:27)

知道问题可能是什么?感谢。

2 个答案:

答案 0 :(得分:1)

当您需要将其保留为String中的二进制数据时,您将响应中的数据视为Buffer。 Node-canvas期望将二进制数据传递到img.src

这应该在您的http响应处理程序中起作用:

var data = new Buffer(parseInt(res.headers['content-length'],10));
var pos = 0;
res.on('data', function(chunk) {
  chunk.copy(data, pos);
  pos += chunk.length;
});
res.on('end', function () {
  img = new canvas.Image;
  img.src = data;
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var out = fs.createWriteStream(__dirname + '/my-out.png')
    , stream = outCanvas.createPNGStream();

  stream.on('data', function(chunk){
    out.write(chunk);
  });
});

答案 1 :(得分:1)

一定是jpg问题(我不知道)我认为如果你的图像是png会好的

请安装libjpeg来解决问题:)