1

So I want to use the sharp package in combination with canvas to process and draw some images in Nodejs. When I try to load an image using sharp like this:

const buffer = await sharp("E:/PathToProject/image_150x150.png").toFormat('png').toBuffer()

then the programm just crashes without any output. So wrapping it in a try-catch block doesn't output anything. Also, using .then().catch() instead of async/await doesn't help as well. What i've tried so far:

const buffer = await sharp("E:/PathToProject/image_150x150.png")
    .png()
    .toBuffer()

const buffer = await sharp("E:/PathToProject/image_150x150.png")
    .toFormat('png')
    .toBuffer()

const { data, info } = await sharp("E:/PathToProject/image_150x150.png")
    .toFormat('png')
    .toBuffer({ resolveWithObject: true })

sharp("E:/PathToProject/image_150x150.png")
    .toFormat('png')
    .toBuffer()
    .then(buffer => {
        console.log("This is never printed")
    })
    .catch(err => {
        console.error("This is also never printed")
    })

The above examples are from the docs. By doing each step of the chain in a separate line, I figured out that toBuffer() crashes the program. Does somebody have a clue what is going wrong here?

HimmDawg
  • 97
  • 10

1 Answers1

1

I guess, it's because you are trying to convert .png file to the same format:

const buffer = await sharp("E:/PathToProject/image_150x150.png")
    .png() // --> here. Try to use .jpg()
    .toBuffer()

I just tried to do something similar. My program crashes when I try to convert a file with .jpg extention using .jpg() method:

const buffer = await sharp(req.file.jpg) // --> original format
      .resize({ width: 300, height: 300 })
      .jpg() // --> converting to the same format
      .toBuffer();

It results in a type-error:

TypeError: sharp(...).resize(...).jpg is not a function

When I convert to a different format, everything works:

const buffer = await sharp(req.file.jpg) // --> original format
          .resize({ width: 300, height: 300 })
          .png() // --> converting to a different format
          .toBuffer();
an_bozh
  • 45
  • 8