使用 Sharp 调整图像大小时,错误 sharp.resize(...).max 不是函数

Error sharp.resize(...).max is not a function while resizing image with Sharp

我正在尝试使用 sharp 调整图像大小,版本是 "sharp": "^0.23.0"。我使用了 functions-samples 中的示例代码。我的代码在这里

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));
  }

但它因以下错误而终止

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)

似乎 max 和许多其他操作在 v0.21.0 中已弃用并在 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

如果在弃用后提供,您需要寻找替代方案。

为了解决这个错误,我将我的函数 cod 更改为如下:

'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));
});