Reputation: 3279
EDIT: the solution is to use
res.set('Content-Type', 'image/png');
res.end(data, 'binary').
I am trying to dynamically generate images using node-gd. My application is node.js/express.
This code successfully generates an image:
//create image
var gd = require('node-gd');
var img = gd.createSync(200, 80);
img.colorAllocate(0, 255, 0);
img.savePng('../test.png', 0, function(error) {
if (error) throw error;
img.destroy();
})
But it saves the image to a file. I don't necessarily want to keep the generated images, just send it to the client.
I was hoping I could just do
res.send(img);
But that just returns an object with metadata about the image.
EDIT: Attempt at outputting the pointer:
//create image
var gd = require('node-gd');
var img = gd.createSync(200, 80);
img.colorAllocate(0, 255, 0);
var imageData = img.pngPtr();
res.set('Content-Type', 'image/png');
console.log(imageData);
res.send(imageData);
In my browser I get:
The image “URLHERE” cannot be displayed because it contains errors.
The file isn't empty, it's like 138 bytes, where the actual image is like 2kb.
if I log the PNG data (I didn't expect it to be readable, but still):
PNG
IHDRÈPf£¨óPLTEÿ4^À¨ pHYsÄÄ+IDATHc`£`Q0
FÁ( ½1üñIEND®B`
Upvotes: 1
Views: 860
Reputation: 121
send it as a binary:
res.write(buffer,'binary');
res.end(null, 'binary');
The imageptr() generated.
To generate the binary refer this https://github.com/y-a-v-a/node-gd/blob/stable/docs/index.md#saving-graphic-images
I used:
var jpgImageData = img.jpegPtr(0);
Upvotes: 1
Reputation: 19581
You can use the pointer
( the buffer ) of the image via the API.
res.set('Content-Type', 'image/png');
res.send( img.pngPtr() );
You can read more about the functions in the official documentation
Upvotes: 3
Reputation: 591
Would Express's res.sendFile method work for you?
res.sendFile('/path/to/image.png')
Upvotes: 1