2

我正在尝试使用节点画布在 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:名称太长,stat 'data:image/png;base64,iVBORw0 ...'

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

    TypeError:路径必须是字符串。已收到
        在 assertPath (path.js:7:11)
        在 Object.basename (path.js:1362:5)
        在 Bucket.upload (/user_code/node_modules/@google-cloud/storage/src/bucket.js:2259:43)
        在 /user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:777:22
        在 Bucket.wrapper [作为上传] (/user_code/node_modules/@google-cloud/storage/node_modules/@google-cloud/common/src/util.js:761:12)
        在 /user_code/sendTweet.js:107:21

我也尝试toBlob过,但该功能不存在节点画布的服务器端。

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

谢谢!

4

0 回答 0