-
-
Save tgmarinho/3313612d1389c5a1042605ae26eec719 to your computer and use it in GitHub Desktop.
Get dimension of an image object uploaded to firebase storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const functions = require('firebase-functions'); | |
const mkdirp = require('mkdirp-promise'); | |
const admin = require('firebase-admin'); | |
const { execFile } = require('child-process-promise'); | |
const path = require('path'); | |
const os = require('os'); | |
const fs = require('fs'); | |
admin.initializeApp(); | |
exports.getImageDimensions = functions.storage | |
.object() | |
.onFinalize(async object => { | |
// File and directory paths. | |
const { name: filePath, contentType } = object; | |
console.log(object); | |
const tempLocalFile = path.join(os.tmpdir(), filePath); | |
const tempLocalDir = path.dirname(tempLocalFile); | |
// Exit if this is triggered on a file that is not an image. | |
if (!contentType.startsWith('image/')) { | |
return console.log('This is not an image.'); | |
} | |
// Cloud Storage files. | |
const bucket = admin.storage().bucket(object.bucket); | |
const file = bucket.file(filePath); | |
// Create the temp directory where the storage file will be downloaded. | |
await mkdirp(tempLocalDir); | |
// Download file from bucket. | |
await file.download({ destination: tempLocalFile }); | |
console.log('The file has been downloaded to', tempLocalFile); | |
// Get Dimensions of the image | |
const { stdout } = await execFile( | |
'identify', | |
['-format', '%wx%h', tempLocalFile], | |
{ | |
capture: ['stdout', 'stderr'], | |
} | |
); | |
const [height, width] = stdout.split('x'); | |
console.log(`Height:${height}Width:${width}`); | |
fs.unlinkSync(tempLocalFile); | |
return console.log('Done'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment