简体   繁体   中英

How can I save a Google Chart PNG with PHP?

I have a chart that I have generated with Google Charts API which I would like to save as an image file. I use PHP to save it to a file, but it isnt valid.

What do I need to do.

javascript

 var chart = new google.visualization.PieChart(document.getElementById('chart_div_source'));
 chart.draw(data, {width: 450, height: 300, title: 'Course Payment Breakdown'});

 jQuery.post("action_save64png.php", {pngImageData :chart.getImageURI(), CourseID: 23, charttype: 'incomesplit' });

This generates the chart and makes an ajax request to action_save64png.php to save the file

PHP File

$EncodedPNG = $_POST['pngImageData'];
$FileName = 'chart_'. $_POST['CourseID'] . '.png';

$decoded=base64_decode($EncodedPNG);

file_put_contents('../charts/' . $FileName,$decoded);

This saves the file but it is an invalid png when I try to open it.

What do I need to do differntly?

It turns out that there is a string at the begining of a PNG 64bit string

data:image/png;base64,

That must be removed first.

$EncodedPNG = $_POST['pngImageData'];
//Replace spaces with +
$EncodedPNG = str_replace(' ','+',$EncodedPNG);
//Remove identifier string from begining of data.
$EncodedPNG =  str_replace('data:image/png;base64,', '', $EncodedPNG);

$FileName = 'chart_'.  $_POST['CourseID'] .  '.png';


$decoded=base64_decode($EncodedPNG);
file_put_contents('../charts/' . $FileName,$decoded);

Now the png file is valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM