Toby Allen
Toby Allen

Reputation: 11213

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?

Upvotes: 2

Views: 1936

Answers (1)

Toby Allen
Toby Allen

Reputation: 11213

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.

Upvotes: 3

Related Questions