我需要一个我创建的功能来处理用户发送到我的应用程序的图像。
我需要获取用户发送的图像,调整大小并检查图像是否已更改,以避免该功能再次执行。我看到的示例更改了图像名称,并检查了该名称是否与设置的名称相等,但是在我的情况下,我需要保留图片的原始名称,那么,该怎么办?还是存在解决此问题的更好方法? 我的功能代码是:
import * as functions from 'firebase-functions';
import * as Storage from '@google-cloud/storage';
const gcs = new Storage();
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import * as sharp from 'sharp';
import * as fs from 'fs-extra';
export const generateThumbs = functions.storage
.object()
.onFinalize(async object => {
const bucket = gcs.bucket(object.bucket);
const filePath = object.name;
const fileName = filePath.split('/').pop();
const bucketDir = dirname(filePath);
const workingDir = join(tmpdir(), 'thumbs');
const tmpFilePath = join(workingDir, 'source.png');
if (!object.contentType.includes('image')) {
console.log('exiting function');
return false;
}
// 1. Ensure thumbnail dir exists
await fs.ensureDir(workingDir);
// 2. Download Source File
await bucket.file(filePath).download({
destination: tmpFilePath
});
// 3. Resize the images and define an array of upload promises
const sizes = [64, 128, 256];
const uploadPromises = sizes.map(async size => {
const thumbName = `thumb@${size}_${fileName}`;
const thumbPath = join(workingDir, thumbName);
// Resize source image
await sharp(tmpFilePath)
.resize(size, size)
.toFile(thumbPath);
// Upload to GCS
return bucket.upload(thumbPath, {
destination: join(bucketDir, thumbName)
});
});
// 4. Run the upload operations
await Promise.all(uploadPromises);
// 5. Cleanup remove the tmp/thumbs from the filesystem
return fs.remove(workingDir);
});
答案 0 :(得分:0)
如果您需要覆盖原始文件,并且希望避免此功能造成无限循环,则可以在将文件上传回Cloud Storage时将custom metadata附加到文件。然后,当对该文件再次调用该函数时,可以检查metadata on the incoming ObjectMetadata object来了解该函数何时应退出紧急状态而无需进行任何其他更改。