Sharp: Get metadata from resized/modified image.

Created on 28 Oct 2019  路  2Comments  路  Source: lovell/sharp

What are you trying to achieve?
I want to get width, height and size in file system from a resized image. I've tried using the metadata method, but it gives me information about the original image, not the resized image. I wonder if that is possible without having to re-open the image after storing it.

Have you searched for similar questions?
Yes :)

Are you able to provide a standalone code sample that demonstrates this question?

// Resize the image.
var transform = await sharp().resize(resizeOptions).jpeg({ quality: 90 }).toFormat('jpg')
file.stream.pipe(transform)

// Save the image on the file system.
await Drive.disk('spaces').put(path, transform, {
  ACL: 'public-read',
  ContentType: 'image/jpg'
})

// Get image metadata
const metadata = await transform.metadata()
console.log(metadata) // This gives me the original image metadata

Are you able to provide a sample image that helps explain the question?
I don't believe it is necessary.

question

Most helpful comment

Hi, in your sample code, transform refers to the input sharp instance rather than the output JPEG data. You'll need to add a call to toBuffer() to generate the output image, something like (untested):

  // Resize the image.
- var transform = await sharp().resize(resizeOptions).jpeg({ quality: 90 }).toFormat('jpg')
+ const transform = sharp().resize(resizeOptions).jpeg({ quality: 90 }).toFormat('jpg')
  file.stream.pipe(transform)
+ const output = await transform.toBuffer()

  // Save the image on the file system.
- await Drive.disk('spaces').put(path, transform, {
+ await Drive.disk('spaces').put(path, output, {
    ACL: 'public-read',
    ContentType: 'image/jpg'
  })

  // Get image metadata
- const metadata = await transform.metadata()
+ const metadata = await sharp(output).metadata()

All 2 comments

Hi, in your sample code, transform refers to the input sharp instance rather than the output JPEG data. You'll need to add a call to toBuffer() to generate the output image, something like (untested):

  // Resize the image.
- var transform = await sharp().resize(resizeOptions).jpeg({ quality: 90 }).toFormat('jpg')
+ const transform = sharp().resize(resizeOptions).jpeg({ quality: 90 }).toFormat('jpg')
  file.stream.pipe(transform)
+ const output = await transform.toBuffer()

  // Save the image on the file system.
- await Drive.disk('spaces').put(path, transform, {
+ await Drive.disk('spaces').put(path, output, {
    ACL: 'public-read',
    ContentType: 'image/jpg'
  })

  // Get image metadata
- const metadata = await transform.metadata()
+ const metadata = await sharp(output).metadata()

It works! Thank you very much!

Was this page helpful?
0 / 5 - 0 ratings