y-a-v-a / node-gd

🎨 GD graphics library (libgd) C++ bindings for Node.js.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Generate image and send back as image stream

Sebosek opened this issue · comments

Hello,

how can I send generated image back to client and avoid to save image to disk and read it again?
Thank you.

S.

Hi thanks for reaching out, I will give you an example later today. In short, you can use gd.Image#jpegPtr. Take a look at this page in the mean time ;-)
https://github.com/y-a-v-a/node-gd/blob/master/docs/index.md#saving-graphic-images

Not needed, thank you.

private avatar() {
    this.app.get('/', (req: express.Request, res: express.Response) => {
        var avatar = gd.createSync(200, 200);

        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);

        avatar.colorAllocate(r, g, b);
        var data = avatar.jpegPtr(0);
        res.writeHead(200, {'Content-Type': 'image/jpeg'});
        res.end(data, 'binary');

        avatar.destroy();
    });
}
commented
const data = img.jpegPtr(0)
console.log(typeof data) // string

You know, Buffer in the std is what we like, How to get a Buffer instance ?

commented

Thanks to @Sebosek , I got answer

const data = img.jpegPtr(0)
const buf = new Buffer(data, 'binary')