phantom+express

你。 提交于 2020-04-06 02:44:05
var express = require('express');
var router = express.Router();
var phantom = require('phantom');

var web2img = (url, res, dataType, width, height) => {
    phantom.create().then(function (ph) {
        ph.createPage().then((page) => {
            var settings = {
                // operation: "POST",
                encoding: "utf8"
            };
            page.open(url, settings).then((status) => {
                console.log(status);
                var fmt = 'JPEG';
                if (status == 'success') {
                    page.property('viewportSize', {width: width || 540, height: height || 960});
                    page.renderBase64(fmt).then((data) => {
                        if (dataType == 0) {
                            res.json({code: 1, data: "data:image/png;base64," + data});
                        } else if (dataType == 1) {
                            res.send("data:image/png;base64," + data);
                        } else if (dataType == 2) {//文件输出
                            var imageBuffer = new Buffer(data, 'base64');
                            res.send(imageBuffer);
                        }
                    });

                } else {
                    res.json({code: 0, msg: '生成图片异常'});
                }
                ph.exit();
            });
        });
    });
};

router.all('/web2img', function (req, res, next) {
    let url = req.query.url;
    let width = req.query.width;
    let height = req.query.height;
    let dataType = req.query.dataType || 0;
    web2img(url, res, dataType, width, height);
});

module.exports = router;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!