4

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

Shan
  • 180
  • 1
  • 2
  • 13

2 Answers2

8

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');
thammada.ts
  • 5,065
  • 2
  • 22
  • 33
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
})
CrackerKSR
  • 1,380
  • 1
  • 11
  • 29