'Google Cloud Function (Get image dimensions)

I am trying to validate the image dimensions of the posts which are in my firebase storage using a Cloud Function. What I am trying to do is:

1: Let the user upload an image

2: When it is uploaded, the backend checks it dimensions

2.1: If it has good dimensions don't remove it

2.2: Else, remove it from the storage

The code looks like:

// Validate image dimensions
exports.validateImageDimensions = functions
  .region("us-central1")
  .runWith({ memory: "1GB", timeoutSeconds: 120 })
  .storage.object()
  .onFinalize(async (object) => {
    // Get the bucket which contains the image
    const bucket = gcs.bucket(object.bucket);

    // Get the name
    const filePath = object.name;

    // Check if the file is an image
    const isImage = object.contentType.startsWith("image/");

    // Check if the image has valid dimensions
    const hasValidDimensions = true; // TODO: How to get the image dimension?

    // Do nothing if is an image and has valid dimensions
    if (isImage && hasValidDimensions) {
      return;
    }

    try {
      await bucket.file(filePath).delete();

      console.log(
        `The image ${filePath} has been deleted because it has invalid dimensions.`
      );

      // TODO - Remove image's document in firestore
    } catch (err) {
      console.log(`Error deleting invalid file ${filePath}: ${err}`);
    }
});

But I don't know how to get the object dimensions. I have check the documentation but not having answers.

Any ideas?



Solution 1:[1]

Use sharp , here's the documentation that talks about it:

const metadata = await sharp('image.jpg').metadata();

const width = metadata.width;
const height = metadata.height;

functions.logger.log(`width: `, width);
functions.logger.log(`height: `, height);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 edalvb