Can I directly process buffer data using Sharp in NodeJs
Asked Answered
S

2

6

I get buffer data to my program from external and I want to process buffer data and send it as a buffer also. So I don't want to convert buffer into an image. How can I do this?

I try this way but it not work.

const process = await sharp(incoming_buffer_data).grayscale();

fs.writeFileSync('test.jpg', process); // I am using this for testing. Allways I am getting worng image format as an error

Shorten answered 7/7, 2020 at 15:21 Comment(1)
Very, very, very bad! you are overriding the global process variable!Buddhism
H
9

Assuming incoming_buffer_data is indeed a buffer and has a supported image format.

You can either get the output as buffer, and send it to fs.writeFileSync() like you tried to do

const buffer = await sharp(incoming_buffer_data).grayscale().toBuffer();
fs.writeFileSync('test.jpg', buffer);

Or you can write it to a file directly

await sharp(incoming_buffer_data).grayscale().toFile('test.jpg');
Hanks answered 7/7, 2020 at 16:52 Comment(0)
T
0

Working snippet.

sharp(buffer)
  .greyscale()
  .toFile('file.png', (err, info) => {
    // file is stored as file.png in current directory
})

You can even do other thing as well like resizing

sharp(buffer)
  .greyscale()
  .resize(512,512,{fit:'contain'})
  .toFile('file.png', (err, info) => {
    // file is stored as file.png in current directory
})
Trout answered 17/2, 2022 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.