douyao3895
2012-12-11 16:19
浏览 153
已采纳

将Google图表另存为图片

So after hours of websearching, googling and overflowing i can't find the solution to my problem.

I got a linechart from Google charts. I want to convert it to PNG, save it on the server en insert it into a MySQL database.

Sounds simple, but i cant get it to work. The script from this website isnt working anymore (atleast not here) http://www.battlehorse.net/page/topics/charts/save_google_charts_as_image.html -> Not working.

Second option is the old option:

$imageData =     file_get_contents('http://chart.apis.google.com/chart... etc');

I cant use that because its not supported anymore and cant get some decent quality out of it.

Is there anybody here that can give a good tutorial or help for my problem?

EDIT:

I used the code from Battlehorse combined with the code from EriC.

So now i got this working to show the chart as an image in a DIV i want to save this image on the server and update the mysql to use it in the future to use it in PDF files.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dtvam48220 2012-12-11 16:40
    已采纳

    When you visit the site, paste this in the console (overwriting the malfunctioning function).

      function getImgData(chartContainer) {
        var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
        var svg = chartArea.innerHTML;
        var doc = chartContainer.ownerDocument;
        var canvas = doc.createElement('canvas');
        canvas.setAttribute('width', chartArea.offsetWidth);
        canvas.setAttribute('height', chartArea.offsetHeight);
    
    
        canvas.setAttribute(
            'style',
            'position: absolute; ' +
            'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
            'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
        doc.body.appendChild(canvas);
        canvg(canvas, svg);
        var imgData = canvas.toDataURL("image/png");
        canvas.parentNode.removeChild(canvas);
        return imgData;
      }
    

    In JS it was searching for an iframe bla bla to get the svg.


    To automatically save the image, you can just let the method being invoked programmatically.

    document.body.addEventListener("load", function() {
    
            saveAsImg( document.getElementById("pie_div")); // or your ID
    
        }, false );
    


    For saving images serverside, this post could be helpful save a PNG image server-side

    Update
    Posting images to PHP (index.js)

    function saveToPHP( imgdata ) {
    
        var script = document.createElement("SCRIPT");
    
        script.setAttribute( 'type', 'text/javascript' );
        script.setAttribute( 'src', 'save.php?data=' + imgdata );
    
        document.head.appendChild( script );
    }
    
    function save() {
    
        var canvas = document.getElementById("canvas"), // Get your canvas
            imgdata = canvas.toDataURL();
    
        saveToPHP( imgdata );
    }
    
    function drawOnCanvas() {
    
        var canvas = document.getElementById("canvas"), // Get your canvas
            ctx = canvas.getContext("2d");
    
        ctx.strokeStyle = "#000000";
        ctx.fillStyle = "#FFFF00";
        ctx.beginPath();
        ctx.arc(100,99,50,0,Math.PI*2,true);
        ctx.closePath();
        ctx.stroke();
        ctx.fill();
    }
    
    drawOnCanvas(); // Test
    save();
    

    save.php

    <?php
        // Get the request
        $data = $_GET['data'];
    
        // Save to your DB.
    ?>
    
    已采纳该答案
    打赏 评论
  • doupeng3501 2013-05-14 21:57

    You can use the grChartImg library. It's a cross browser solution and supports even old versions of IE (8 and earlier).It has many features such as download image,upload to the server, show the image in a dialog etc.

    For more info look at http://www.chartstoimage.eu.

    i hope help you.

    打赏 评论
  • doudi4137 2013-06-27 14:34

    This is not really an answer but might be one in the future and it is nescesary if you just want the feature back. The following URL shows all the current issues and feature requests for the visualization API.

    https://code.google.com/p/google-visualization-api-issues/issues/list?can=2&q=&sort=-stars+id&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Stars

    The more stars/votes this feature request gets, the higher the chance they will take a look at it.

    打赏 评论
  • dse3168 2015-03-26 08:23

    I have the same issue - Save Google charts as image on server. None of answers here works for me. Finally I get solution but with some bugs(working only in Chrome browser). As base I used script from here https://gist.github.com/mpetherb/7085315 I made some changes for my project. I use jquery for importing generated graph image to to my server. This is a graph that I want to convert to image and save google graph example id="ex0"

    Script for converting to image and importing to server

    <script>
    function getImgData(chartContainer) {
    var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
    var svg = chartArea.innerHTML;
    var doc = chartContainer.ownerDocument;
    var canvas = doc.createElement('canvas');
    canvas.setAttribute('width', chartArea.offsetWidth);
    canvas.setAttribute('height', chartArea.offsetHeight);
    canvas.setAttribute(
    'style',
    'position: absolute; ' +
    'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
    'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
    doc.body.appendChild(canvas);
    canvg(canvas, svg);
    var imgData = canvas.toDataURL("image/png");
    canvas.parentNode.removeChild(canvas);
    return imgData;
    }
    
    function toImg(chartContainer, imgContainer) {
    var doc = chartContainer.ownerDocument;
    var img = doc.createElement('img');
    var myimg=img.src = getImgData(chartContainer);
    //Here I am using jquery for importing decoded image to hidden.php on my server 
    $.ajax({
        method: "POST",
        url: "hidden.php",
        data: { name: myimg } });
    while (imgContainer.firstChild) {
    imgContainer.removeChild(imgContainer.firstChild);
    }
    imgContainer.appendChild(img);
    }
    </script>
    
    <button onclick="toImg(document.getElementById('ex0'), document.getElementById('ex0'));" 
    type="button" <Convert to image and upload on server></button>
    // ex0 - div id of this type of google graph. If you using another type of google graph - you should change it

    Don't forget include jquery to your code.

    and php hidden script for receiving data from jquery method POST and saving it on server

    hidden.php file

    <?php
     if(isset($_POST['name']))
      {   
        $data = $_POST['name'];
    
        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        file_put_contents('graph_temp.png', base64_decode($data));

    I will notice again - works only in Chrome browser. Firefox also create image file on server but without any content (looks like firefox not support base64 encoded data)

    </div>
    
    打赏 评论

相关推荐 更多相似问题