Skip to content

Instantly share code, notes, and snippets.

@eusthace811
Forked from codediodeio/index.js
Created April 17, 2019 13:52
Show Gist options
  • Save eusthace811/923a365e56f26e08b82cacfe9e1e0281 to your computer and use it in GitHub Desktop.
Save eusthace811/923a365e56f26e08b82cacfe9e1e0281 to your computer and use it in GitHub Desktop.

Revisions

  1. @codediodeio codediodeio created this gist Jun 28, 2017.
    59 changes: 59 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    const functions = require('firebase-functions');
    const gcs = require('@google-cloud/storage')();
    const sharp = require('sharp')
    const _ = require('lodash');
    const path = require('path');
    const os = require('os');

    exports.generateThumbnail = functions.storage.object('uploads/{imageId}').onChange(event => {

    const object = event.data; // The Storage object.

    console.log(object)

    const fileBucket = object.bucket; // The Storage bucket that contains the file.
    const filePath = object.name; // File path in the bucket.
    const contentType = object.contentType; // File content type.
    const resourceState = object.resourceState; // The resourceState is 'exists' or 'not_exists' (for file/folder deletions).
    const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.

    const SIZES = [64, 256, 512]; // Resize target width in pixels

    if (!contentType.startsWith('image/') || resourceState == 'not_exists') {
    console.log('This is not an image.');
    return;
    }

    if (_.includes(filePath, '_thumb')) {
    console.log('already processed image');
    return;
    }


    const fileName = filePath.split('/').pop();
    const bucket = gcs.bucket(fileBucket);
    const tempFilePath = path.join(os.tmpdir(), fileName);

    return bucket.file(filePath).download({
    destination: tempFilePath
    }).then(() => {

    _.each(SIZES, (size) => {

    let newFileName = `${fileName}_${size}_thumb.png`
    let newFileTemp = path.join(os.tmpdir(), newFileName);
    let newFilePath = `thumbs/${newFileName}`

    sharp(tempFilePath)
    .resize(size, null)
    .toFile(newFileTemp, (err, info) => {

    bucket.upload(newFileTemp, {
    destination: newFilePath
    });

    });

    })
    })
    })
    13 changes: 13 additions & 0 deletions package.json
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    {
    "name": "functions",
    "description": "Cloud Functions for Firebase",
    "dependencies": {
    "@google-cloud/storage": "^0.4.0",
    "firebase-admin": "^4.1.2",
    "firebase-functions": "^0.5",
    "lodash": "^4.17.4",
    "request-promise": "^2.0.0",
    "sharp": "^0.18.1"
    },
    "private": true
    }