drvonr6573 2014-03-09 09:15
浏览 56

如何使用PHP保存Google Chart PNG?

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?

  • 写回答

1条回答 默认 最新

  • douyuan9512 2014-03-09 09:15
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?