4

I'm trying to resize an image with sharp, version is "sharp": "^0.23.0". I used the sample code from functions-samples. My code is here

thumbnailGeneratorSharp: async (object) => {
    const fileBucket = object.bucket; // The Storage bucket that contains the file.
    const filePath = object.name; // File path in the bucket.
    const contentType = object.contentType; // File content type.

    // Exit if this is triggered on a file that is not an image.
    if (!contentType.startsWith('image/')) {
      console.log('This is not an image.');
      return null;
    }

    // Get the file name.
    const fileName = path.basename(filePath);
    // Exit if the image is already a thumbnail.
    if (fileName.startsWith('thumb_')) {
      console.log('Already a Thumbnail.');
      return null;
    }

    // Download file from bucket.
    const bucket = gcs.bucket(fileBucket);

    const metadata = {
      contentType: contentType,
    };
    // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
    const thumbFileName = `thumb_${fileName}`;
    const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
    // Create write stream for uploading thumbnail
    const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({ metadata });

    // Create Sharp pipeline for resizing the image and use pipe to read from bucket read stream
    const pipeline = sharp();
    pipeline.resize(THUMB_MAX_WIDTH, THUMB_MAX_HEIGHT).max().pipe(thumbnailUploadStream);

    bucket.file(filePath).createReadStream().pipe(pipeline);

    return new Promise((resolve, reject) =>
      thumbnailUploadStream.on('finish', resolve).on('error', reject));
  }

But it terminates with the following error

TypeError: pipeline.resize(...).max is not a function at thumbnailGeneratorSharp (/srv/imageUtil.js:120:56) at cloudFunctionNewSignature (/srv/node_modules/firebase-functions/lib/cloud-functions.js:120:23) at /worker/worker.js:825:24 at at process._tickDomainCallback (internal/process/next_tick.js:229:7)

2 Answers 2

9

To solve the error, I changed my function cod to bellow:

'use strict';
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();
const path = require('path');
const sharp = require('sharp');

const THUMB_MAX_WIDTH = 200;
const THUMB_MAX_HEIGHT = 200;


/**
 * When an image is uploaded in the Storage bucket 
 *We generate a thumbnail automatically using
  *Sharp.
 */
exports.generateThumbnail = functions.storage.object().onFinalize((object) => {
  const fileBucket = object.bucket; // The Storage bucket that contains the file.
  const filePath = object.name; // File path in the bucket.
  const contentType = object.contentType; // File content type.

  // Exit if this is triggered on a file that is not an image.
  if (!contentType.startsWith('image/')) {
    console.log('This is not an image.');
    return null;
  }

  // Get the file name.
  const fileName = path.basename(filePath);
  // Exit if the image is already a thumbnail.
  if (fileName.startsWith('thumb_')) {
    console.log('Already a Thumbnail.');
    return null;
  }

  // Download file from bucket.
  const bucket = admin.storage().bucket(fileBucket);
  //const bucket = gcs.bucket(fileBucket);

  const metadata = {
    contentType: contentType,
  };
  // We add a 'thumb_' prefix to thumbnails file name. That's where we'll upload the thumbnail.
  const thumbFileName = `thumb_${fileName}`;
  const thumbFilePath = path.join(path.dirname(filePath), thumbFileName);
  // Create write stream for uploading thumbnail
  const thumbnailUploadStream = bucket.file(thumbFilePath).createWriteStream({metadata});

//Beacause the function max() is removed for newer version
//I use this from https://sharp.pixelplumbing.com/api-resize
const transformer = sharp()
  .resize({
    width: THUMB_MAX_WIDTH,
    height: THUMB_MAX_HEIGHT,
    fit: sharp.fit.inside,
    position: sharp.strategy.entropy
  });

  //reading from readable stream
  //writing to writable stream
  bucket.file(filePath).createReadStream()
    .pipe(transformer)
    .pipe(thumbnailUploadStream);

  return new Promise((resolve, reject) =>
      thumbnailUploadStream.on('finish', resolve).on('error', reject));
});

Sign up to request clarification or add additional context in comments.

Comments

1

It seems max and many other operations were deprecated in v0.21.0 and removed in v0.22.0

http://sharp.pixelplumbing.com/en/stable/changelog/#v0210-4th-october-2018 http://sharp.pixelplumbing.com/en/stable/changelog/#v0220-18th-march-2019

You need to look for an alternative if provided after deprecation.

2 Comments

The first link provides the migration instructions. :)
Yes, even I'm scared now as I have used sharp max-min in a lot of projects and reviewing them, thanks for the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.