【问题标题】:Google Cloud Function (Get image dimensions)谷歌云函数(获取图片尺寸)
【发布时间】:2020-07-04 03:09:20
【问题描述】:

我正在尝试使用云函数验证我的 Firebase 存储中帖子的图像尺寸。我想做的是:

1:让用户上传图片

2:上传后,后端检查尺寸

2.1:如果它具有良好的尺寸,请不要删除它

2.2:否则,将其从存储中删除

代码如下:

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

但我不知道如何获取对象尺寸。我检查了文档但没有答案。

有什么想法吗?

【问题讨论】:

  • 我认为我必须为维度创建自定义元数据,但要寻找更容易的东西
  • 您将不得不查找并使用图像处理库来查找有关图像的信息,例如Sharp 或imagemagick。
  • @VictorMolina 我很好奇,你最后做了什么?我也面临这个问题

标签: node.js firebase google-cloud-functions google-cloud-storage


【解决方案1】:

使用 sharp ,这里是 documentation 谈论它:

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

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2017-06-26
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多