通过通过ajax发送的dataURI使用php生成png文件 [英] Generate png-file with php from dataURI sent through ajax
问题描述
我有一个svg文件,该文件正在生成dataURI-png,并且效果很好.而且我希望将dataURI保存为图像,因此我尝试通过ajax将dataURI发送到可以执行PHP的另一台服务器.但是我无法正常工作.
I have an svg file that is generating a dataURI-png and that works great. And I want that dataURI to be saved as an image, therefore I try to send the dataURI through ajax to another server that can execute PHP. But I can't get it to work.
这是用于生成dataURI的代码(有效)
This is the code for generating the dataURI (that works)
var mySVG = document.querySelector('svg'), // Inline SVG element
tgtImage = document.querySelector('.tgtImage'); // Where to draw the result
can = document.createElement('canvas'), // Not shown on page
ctx = can.getContext('2d'),
loader = new Image; // Not shown on page
console.log(mySVG);
loader.width = can.width = tgtImage.width;
loader.height = can.height = tgtImage.height;
loader.onload = function(){
ctx.drawImage( loader, 0, 0, loader.width, loader.height );
tgtImage.src = can.toDataURL("image/png");
};
这是将其发送到外部php服务器的ajax代码:
This is the ajax-code to send it to the external php-server:
$.ajax({
type: "POST",
data: {id:'testID',datauri: can.toDataURL("image/png")},
crossDomain: true,
//dataType: "jsonp",
url: "https://urltoscript.php",
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
用于生成png的PHP代码
The PHP-code to generate the png
$dataUrl = $_REQUEST['datauri'];
$id = $_REQUEST['id'];
list($meta, $content) = explode(',', $dataUrl);
$content = base64_decode($content);
file_put_contents('./tmp-png/'.$id.'.png', $content);
手动插入dataURI时,将生成PNG代.但这不适用于上面的ajax函数.
The PNG-generation works when manualy inserting the dataURI. But it doesn't work with the ajax function above.
谢谢!
推荐答案
$dataUrl = $_REQUEST['datauri'];
$id = $_REQUEST['id'];
list($meta, $content) = explode(',', $dataUrl);
$content = str_replace(".", "", $content); // some android browsers will return a data64 that may not be accurate without this without this.
$content = base64_decode($content);
$image = imagecreatefromstring($content);
imagepng($image, './tmp-png/'.$id.'.png', 90); // Third parameter is optional. Just placed it incase you want to save storage space...
这篇关于通过通过ajax发送的dataURI使用php生成png文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!