使用云函数制作缩略图并将其放置在Firebase存储中的特定文件夹中,可以按照以下步骤进行:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const { Storage } = require('@google-cloud/storage');
const sharp = require('sharp');
admin.initializeApp();
exports.generateThumbnail = functions.storage.object().onFinalize(async (object) => {
const bucket = admin.storage().bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const bucketDir = 'thumbnails';
if (fileName.startsWith('thumb_')) {
console.log('Already a thumbnail');
return null;
}
const workingDir = '/tmp';
const tempFilePath = `${workingDir}/${fileName}`;
await bucket.file(filePath).download({
destination: tempFilePath,
});
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = `${workingDir}/${thumbFileName}`;
const thumbFileBucket = bucket.file(`${bucketDir}/${thumbFileName}`);
await sharp(tempFilePath)
.resize(200, 200)
.toFile(thumbFilePath);
await bucket.upload(thumbFilePath, {
destination: thumbFileBucket,
});
return thumbFileBucket.makePublic();
});
需要注意的是,以上示例代码是使用Google Cloud Storage和Firebase的云函数平台,如果你使用的是腾讯云,可以参考腾讯云函数(SCF)的文档和相关产品进行相应的实现。
推荐的腾讯云相关产品:腾讯云函数(SCF)、腾讯云对象存储(COS)。
腾讯云函数(SCF)产品介绍链接地址:https://cloud.tencent.com/product/scf
腾讯云对象存储(COS)产品介绍链接地址:https://cloud.tencent.com/product/cos
领取专属 10元无门槛券
手把手带您无忧上云