3

i am using sharp.js for image manipulation in node.js

my code

sharp(path)
        .toFormat('jpeg')
        .toBuffer((err, data, info) => {
            fs.writeFile(temp, buffer, { flag: 'w' }, function() {
                response.sendFile(temp);
            });
        });

here temp in fs means "the path" var temp= imageDir + request.params.id; ( http://localhost:2000/images/we.png )

  1. upload image as png format or any other format

  2. convert that image to JPEG using .toFormat('jpeg') and send to buffer

  3. want to save that image from buffer to
User_3535
  • 826
  • 1
  • 13
  • 30

2 Answers2

3

Your code doesn't have 'buffer'. You should be writing data.

.toBuffer((err, data, info) => {
        fs.writeFile(temp, data, { flag: 'w' }, function() {
            response.sendFile(temp);
        });
    });

but you'd be better off using toFile instead of toBuffer:

sharp('originalFile.jpg').
        resize(330,null).
        flatten().
        toFile('newFile.jpg', function(err){
            if(err){
                response.sendStatus(500);
                return;
            }
            response.sendFile('newFile.jpg');
        });
bknights
  • 14,408
  • 2
  • 18
  • 31
  • thank you but ., what if i upload a jpg and convert to png ? .. file format was what ever we want ., – User_3535 Jun 20 '18 at 21:20
  • Then manipulate newFile.jpg to have the correct extension. If your variable `temp` already reflects the desired file type in its extension then just use that. Otherwise fix it. – bknights Jun 20 '18 at 21:21
  • okay so if i want to process a image with extension .webp to tiff ., okay the file name should not change the as of original name ., what if i can do ? – User_3535 Jun 20 '18 at 21:25
  • file name are of dynamic one ., then toFile are of too dynamic based on query parameter – User_3535 Jun 20 '18 at 21:26
1

You can do this

sharp(req.files[0].path).resize(400, 200).toFile('uploads/' + 'thumbnail-' + req.files[0].originalname, (err, sharp) => {
            if (err) {
                console.error(err);
            }
            else {
                console.log(sharp);
            }
        });
Prathamesh More
  • 1,470
  • 2
  • 18
  • 32