I'm in the process of developing functionality to generate thumbnails based on an uploaded file. However, I'm uncertain if my current approach is the most efficient way to accomplish this task. The section of code
if (fileName.startsWith(THUMB_PREFIX)) {
seems to be causing issues as it continuously produces thumbnails.
Is there a simpler method to create multiple thumbnails using this particular example? You can refer to the following link for more information: https://github.com/firebase/functions-samples/blob/master/generate-thumbnail/functions/index.js
exports.onFileChange = functions.storage.object()
.onFinalize((object) => {
const sizes = [200, 50];
const timestamp = + new Date();
sizes.forEach((size, index) => {
// File and directory paths.
const filePath = object.name;
const contentType = object.contentType; // This is the image MIME type
const fileDir = path.dirname(filePath);
let fileName = path.basename(filePath);
let newFileName = path.basename(filePath)
let currentThumbURL = '';
const filename = fileName.substr(0, fileName.indexOf('.'));
let fileExtension = fileName.split('.').pop();
fileName = filename + timestamp + '.' + fileExtension;
const thumbFilePath = path.normalize(path.join(fileDir, `${THUMB_PREFIX}-${size}-${fileName}`));
const tempLocalFile = path.join(os.tmpdir(), filePath);
const tempLocalDir = path.dirname(tempLocalFile);
const tempLocalThumbFile = path.join(os.tmpdir(), thumbFilePath);
var folder = fileDir.substr(0, fileDir.indexOf('/'));
if (folder !== 'profile') return null;
if (!contentType.startsWith('image/')) {
console.log('This is not a profile image.');
return null;
}
// Exit if the image is already a thumbnail.
if (fileName.startsWith(THUMB_PREFIX)) {
console.log('Already a Thumbnail.');
return null;
}
// Cloud Storage files
const bucket = gcs.bucket(object.bucket);
const file = bucket.file(filePath);
const thumbFile = bucket.file(thumbFilePath);
const metadata = {
contentType: contentType,
};
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
return file.download({ destination: tempLocalFile });
}).then(() => {
console.log('The file has been downloaded to', tempLocalFile);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [tempLocalFile, '-thumbnail', `${size}x${size}>`, tempLocalThumbFile], { capture: ['stdout', 'stderr'] });
}).then(() => {
console.log('Thumbnail created at', tempLocalThumbFile);
// Uploading the Thumbnail.
return bucket.upload(tempLocalThumbFile, { destination: thumbFilePath, metadata: metadata });
}).then(() => {
console.log('Thumbnail uploaded to Storage at', thumbFilePath);
// Once the image has been uploaded delete the local files to free up disk space.
console.log('Delet tempLocalFile', tempLocalFile)
console.log('Delete tepLocalThumbFile', tempLocalThumbFile)
fs.unlinkSync(tempLocalFile);
fs.unlinkSync(tempLocalThumbFile);
// Get the Signed URLs for the thumbnail and original image.
const config = {
action: 'read',
expires: '03-01-2500',
};
return Promise.all([
thumbFile.getSignedUrl(config),
file.getSignedUrl(config),
]);
}).then((results) => {
const thumbResult = results[0];
const originalResult = results[1];
const thumbFileUrl = thumbResult[0];
const fileUrl = originalResult[0];
// Add the URLs to the Database
...
}).then(() => {
console.log('Thumbnail URLs saved to database. Delete original uploaded image.')
}
).catch(error => console.log(error));
});
});