2

I am working on an app that uses sharp for processing photos. Currently, when we resize and then write to buffer an image with sharp resize and toBuffer, by default the two of them wipe the EXIF data. We want to remove all metadata except for orientation (if it exists).

I've read sharp's documentation and withMetadata seems to be the candidate to achieve what I want, the problem is that withMetadata preserves all metadata and I just want the orientation of the original image.

The original line of code is

await this.sharpInstance.resize(maxDimension, maxDimension).max().toBuffer()

I think that what I want is something like

await this.sharpInstance.withMetadata().resize(maxDimension, maxDimension).max().withMetadata().toBuffer()

but only for orientation metadata.

I would really appreciated some help to solve this. Thanks very much!

nelson2tm
  • 167
  • 8
  • 16
user156441
  • 175
  • 1
  • 6

2 Answers2

6

A workaround for those not specifically interested in keeping the file's original rotation plus rotation metadata: Rotate the image so that the file has no metadata, but the rotation is correct.

To do this, it is not necessary to read the metadata, if you call the rotate() method without parameters, it will look up the information in the metadata and perform the appropriate rotation.

Gonzalingui
  • 1,357
  • 14
  • 18
5

Have you tried await this.sharpInstance.resize(maxDimension, maxDimension).max().withMetadata().toBuffer() as Sharp docs about withMetadata.

Edited:

I got that. So as withMetadata, first we need to save the orientation metadata and then assign to output buffer later:

// First, save the orientation for later use
const { orientation } = await this.sharpInstance.metadata();

// Then output to Buffer without metadata
// then create another Sharp instance 
// from output Buffer which doesn't have metadata
// and assign saved orientation along with it
sharp(this.sharpInstance.toBuffer())
    .withMetadata({ orientation }).toBuffer();
Nhan Hoang
  • 137
  • 2
  • The problem of this is that it will preserve all existing metadata but what I need is to remove all of the metadata except for the orientation – user156441 Jun 19 '20 at 15:53
  • Perfect! That is exactly what I was looking for. I got confused and thought that withMetadata kept all the attributes. Thanks you for the help! – user156441 Jun 19 '20 at 17:55
  • My only doubt is, why not after saving the original orientation directly do: await this.sharpInstance.withMetadata({orientation}).resize(maxDimension, maxDimension).max().toBuffer() ? – user156441 Jun 19 '20 at 17:58