将节点画布图像保存到firebase服务器

时间:2018-01-02 16:13:58

标签: node.js firebase-storage node-canvas

我尝试使用node-canvas在Google Firebase服务器上创建和映像,并将其存储在Firebase存储中。

const functions = require('firebase-functions');
const admin = require('firebase-admin');

const gcs = require('@google-cloud/storage')();

const path = require('path');
const Canvas = require('canvas-prebuilt');

const env = require('dotenv').config();

try {admin.initializeApp(functions.config().firebase);} catch(e) {}

//Trigger on creation of a new post
exports.default = functions.database.ref('/posts/{postId}').onCreate(event => {

    //Get the postID
    const postId = event.params.postId;

    console.log('We have a new post ' + postId);

    //Get data from the postid
    return admin.database().ref('/posts/' + postId).once('value').then(function(snapshot) {
        const text = snapshot.val().text;

        const canvas = new Canvas(1024, 512);
        const ctx = canvas.getContext('2d');

        //Draw Background
        ctx.fillStyle = '#000';
        ctx.fillRect(0, 0, 1024 , 512);

        //Draw Text
        ctx.font = 'bold 66px Arial';
        ctx.textAlign = 'center';
        ctx.fillStyle = '#fff';
        ctx.fillText(text, 120, 256, 784);

        // Use the postID to name the file Ex : -L1rVJUAtSbc_FampT0D.png
        var filename = postId + '.png';

        // Create the file metadata
        var metadata = {
          contentType: 'image/png'
        };

        const bucket = gcs.bucket('images');
        const filePath = 'images/' + filename;

        return canvas.toDataURL('image/png', function(err, png){

            //Save on Firebase Storage
            return bucket.upload(png, {
            destination: filePath,
            metadata: metadata
            }).then(() => {

                console.log('Image uploaded to Storage at ', filePath);

            });

        });

    });

});

但是,当我尝试使用toDataURL保存时,我收到此错误:

    ENAMETOOLONG: name too long, stat 'data:image/png;base64,iVBORw0 ...'

当我尝试toBuffer时,我得到了这个:

    TypeError: Path must be a string. Received 
        at assertPath (path.js:7:11)
        at Object.basename (path.js:1362:5)
        at Bucket.upload (/user_code/node_modules/@google-cloud/storage/src/bucket.js:2259:43)
        at /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:777:22
        at Bucket.wrapper [as upload] (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:761:12)
        at /user_code/sendTweet.js:107:21

我也尝试toBlob但是该功能并不存在于带有node-canvas的服务器端。

任何人都知道在将图像服务器端传输到Firebase存储之前应该如何保存它?

谢谢!

0 个答案:

没有答案