谷歌云函数(获取图像尺寸)



我正在尝试使用云函数验证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}`);
}
});

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

有什么想法吗?

使用尖锐,这是讨论它的文档:

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

相关内容

  • 没有找到相关文章

最新更新