在Firebase云函数中创建方形缩略图,可以通过以下步骤实现:
firebase functions:create thumbnail
这将创建一个名为"thumbnail"的云函数。
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { Storage } = require('@google-cloud/storage');
const sharp = require('sharp');
admin.initializeApp();
exports.thumbnail = functions.storage.object().onFinalize(async (object) => {
const fileBucket = object.bucket;
const filePath = object.name;
const contentType = object.contentType;
const fileName = filePath.split('/').pop();
const bucket = admin.storage().bucket(fileBucket);
const tempFilePath = `/tmp/${fileName}`;
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
if (fileName.startsWith('thumb_')) {
console.log('Already a Thumbnail.');
return null;
}
await bucket.file(filePath).download({
destination: tempFilePath,
});
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = filePath.replace(fileName, thumbFileName);
const thumbFileBucket = bucket.file(thumbFilePath);
await sharp(tempFilePath)
.resize(200, 200)
.toFile(tempFilePath);
await bucket.upload(tempFilePath, {
destination: thumbFilePath,
metadata: {
contentType: contentType,
},
});
return thumbFileBucket.makePublic();
});
这段代码使用了Firebase的Cloud Storage和Sharp库来处理图像。它会在上传图片后,自动创建一个方形缩略图,并将其上传到相同的存储桶中。
firebase deploy --only functions
这将部署你的云函数,并为其分配一个URL。
现在,当你在Firebase的Cloud Storage中上传一张图片时,云函数将自动创建一个方形缩略图,并将其保存在相同的存储桶中。你可以根据实际需求修改代码中的缩略图尺寸和命名规则。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云