创建Phantomjs导出服务器以将高图转换为图像base64字符串

时间:2014-06-24 12:27:43

标签: jquery html json highcharts phantomjs

我在网上搜索了很多以及之前的stackoverflow问题和答案,但我无法创建图像base64字符串。

  1. 首先我下载phantomjs 1.9.7.0
  2. 我按照here所述启动了phantomj。

    phantomjs highcharts-convert.js -host 127.0.0.1 -port 3003
    
  3. 我创建了html页面并发布如下:

    $(document).ready(function() {
        $("#Button1").click(function() {
            var options = {
                exporting: {
                url: 'http://127.0.0.1:3003'
                },
                xAxis: {
                    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                },
                series: [{data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]}]
                };
                var obj = {},
                exportUrl = options.exporting.url;
                obj.options = JSON.stringify(options);
                obj.type = 'image/png';
                obj.async = true;
    
                $.ajax({
                    type: 'post',
                    url: exportUrl,
                    data: obj,
                    success: function(data) {
                        var imgContainer = $("#imgContainer");
                        $('<img>').attr('src', exportUrl + data).attr('width', '250px').appendTo(imgContainer);
                    },
                    error: function(data) {
                        document.write(JSON.stringify(data));
                    }
    
                });
            });
    
        });
    

    并且(alert(JSON.stringify(data)))

    总是出错
    {"readyState":0,"responseText":"","status":0,"statusText":"error"}
    
  4. 你能帮我吗?

1 个答案:

答案 0 :(得分:1)

尝试解决方案:

$('#export').click(function () {
    var options = {
        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]
    };

    var obj = {
        async: true,
        infile: JSON.stringify(options) // options must be a string, and use infile, not options, like described in docs
    };

    $.ajax({
        type: 'POST',
        data: JSON.stringify(obj), // the same for data property !
        url: 'http://127.0.0.1:3003/',
        success: function (data) {
            $('#imgContainer').html('<img src="' + data + '"/>');
        }
    });
});

编辑:

如果您尝试从不同的域获取图像,请不要忘记CORS:

render(params, function (result) {
    response.statusCode = 200;
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    response.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    response.write(result);
    response.close();
});