LearnBoost/node-canvas — Issue #122: Image fails to render
Author: kangax
Created: 2011-10-15 18:15:28+00:00
State: open

Here's a simplified test case, where one image renders and another one fails (`url` vs `url2`). Both images open fine in a browser (and can be downloaded and viewed locally).

Image fails with "Error: Image given has not completed loaded".

I'm not 100% sure if the problem is with node-canvas. Would appreciate any pointers!

var Canvas = require('canvas')
, Image = Canvas.Image
, canvas = new Canvas(500, 500)
, ctx = canvas.getContext('2d')
, fs = require('fs')
, URL = require('url')
, HTTP = require('http')
, url = 'http://s3-eu-west-1.amazonaws.com/printio/assets/images/large/9c6af4fc958a1967eaa4dba1200fef75ca2f68e9.png'
, url2 = 'https://www.google.com/intl/en_com/images/srpr/logo3w.png';

function request(url, encoding, callback) {
var oURL = URL.parse(url),
client = HTTP.createClient(80, oURL.hostname),
request = client.request('GET', oURL.pathname, { 'host': oURL.hostname });

request.end();
request.on('response', function (response) {
var body = "";
if (encoding) {
response.setEncoding(encoding);
}
response.on('end', function () {
callback(body);
});
response.on('data', function (chunk) {
if (response.statusCode == 200) {
body += chunk;
}
});
});
}

request(url2, 'binary', function(body) {
var img = new Image();
img.src = new Buffer(body, 'binary');

ctx.drawImage(img, 0, 0);

var out = fs.createWriteStream(__dirname + '/output.png')
, stream = canvas.createPNGStream();

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