cloud functions firebase has nice sample create thumbnail each uploaded image. done making use of imagemagick.
i tried convert sample convert pdfs images. imagemagick can do, can't make work cloud functions firebase. keep getting code 1 error:
childprocesserror: `convert /tmp/cd9d0278-16b2-42be-aa3d-45b5adf89332.pdf[0] -density 200 /tmp/cd9d0278-16b2-42be-aa3d-45b5adf89332.pdf` failed code 1 @ childprocess.<anonymous> (/user_code/node_modules/child-process-promise/lib/index.js:132:23) @ emittwo (events.js:106:13) @ childprocess.emit (events.js:191:7) @ maybeclose (internal/child_process.js:877:16) @ socket.<anonymous> (internal/child_process.js:334:11) @ emitone (events.js:96:13) @ socket.emit (events.js:188:7) @ pipe._handle.close [as _onclose] (net.js:498:12)
of course 1 possibility converting pdfs not supported.
const functions = require('firebase-functions'); const gcs = require('@google-cloud/storage')(); const spawn = require('child-process-promise').spawn; // [end import] // [start generatethumbnail] /** * when image uploaded in storage bucket generate thumbnail automatically using * imagemagick. */ // [start generatethumbnailtrigger] exports.generatethumbnail = functions.storage.object().onchange(event => { // [end generatethumbnailtrigger] // [start eventattributes] const object = event.data; // storage object. const filebucket = object.bucket; // storage bucket contains file. const filepath = object.name; // file path in bucket. const contenttype = object.contenttype; // file content type. const resourcestate = object.resourcestate; // resourcestate 'exists' or 'not_exists' (for file/folder deletions). // [end eventattributes] // [start stopconditions] // exit if triggered on file not image. if (!contenttype.startswith('application/pdf')) { console.log('this not pdf.'); return; } // file name. const filename = filepath.split('/').pop(); // exit if image thumbnail. if (filename.startswith('thumb_')) { console.log('already thumbnail.'); return; } // exit if move or deletion event. if (resourcestate === 'not_exists') { console.log('this deletion event.'); return; } // [end stopconditions] // [start thumbnailgeneration] // download file bucket. const bucket = gcs.bucket(filebucket); const tempfilepath = `/tmp/${filename}`; return bucket.file(filepath).download({ destination: tempfilepath }).then(() => { console.log('pdf downloaded locally to', tempfilepath); // generate thumbnail of first page using imagemagick. return spawn('convert', [tempfilepath+'[0]' ,'-density', '200', tempfilepath]).then(() => { console.log('thumbnail created at', tempfilepath); // convert pdf extension png const thumbfilepath = filepath.replace('.pdf', 'png'); // uploading thumbnail. return bucket.upload(tempfilepath, { destination: thumbfilepath }); }); }); // [end thumbnailgeneration] });
Comments
Post a Comment