Skip to content

Instantly share code, notes, and snippets.

@kooba
Last active November 17, 2023 10:17
Show Gist options
  • Save kooba/8e0a9f5ed8dd0366ceb7c47785b8a538 to your computer and use it in GitHub Desktop.
Save kooba/8e0a9f5ed8dd0366ceb7c47785b8a538 to your computer and use it in GitHub Desktop.
Resize image after upload to Firebase Storage bucket. Maintain access token of original image.
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import * as fs from "fs";
import sharp from "sharp";
export const resizeImage = functions.storage
.object()
.onFinalize(async (object) => {
const bucket = admin.storage().bucket(object.bucket);
const filePath = object.name;
const fileName = filePath?.split("/").pop();
const bucketDir = filePath?.substring(0, filePath.lastIndexOf("/"));
// Exit if this is triggered on a file that is not an image.
if (!object.contentType?.startsWith("image/")) {
return functions.logger.log("This is not an image.");
}
// Exit if the image is already a thumbnail.
if (fileName?.startsWith("thumb_")) {
return functions.logger.log("Already a Thumbnail.");
}
functions.logger.log(
`Downloading ${fileName} from bucket ${object.bucket}/${filePath}`,
);
const tempFilePath = `/tmp/${fileName}`;
await bucket.file(filePath!).download({ destination: tempFilePath });
// Resize using Sharp and upload to the same bucket.
const thumbFileName = `thumb_${fileName}`;
const thumbFilePath = bucketDir
? `${bucketDir}/${thumbFileName}`
: thumbFileName;
const tempThumbFilePath = `/tmp/${thumbFileName}`;
functions.logger.log(
`Resizing image ${tempFilePath} to ${tempThumbFilePath}`,
);
await sharp(tempFilePath)
.resize(300, 300, { fit: "inside", withoutEnlargement: true })
.toFile(tempThumbFilePath);
const metadata = {
contentType: object.contentType,
metadata: object.metadata!,
};
// If there's an access token, include it in the metadata
if (object.metadata?.firebaseStorageDownloadTokens) {
metadata.metadata.firebaseStorageDownloadTokens =
object.metadata.firebaseStorageDownloadTokens;
}
// Upload the Thumbnail to Firebase Storage
functions.logger.log(`Uploading thumbnail to ${thumbFilePath}`);
await bucket.upload(tempThumbFilePath, {
destination: thumbFilePath,
metadata: metadata,
});
functions.logger.log(`Deleting ${tempFilePath} and ${tempThumbFilePath}`);
fs.unlinkSync(tempFilePath);
fs.unlinkSync(tempThumbFilePath);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment