PHP Data-URI to file

只谈情不闲聊 提交于 2019-11-26 15:59:49
Paul S.

A quick look at the PHP manual yields the following:

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decodedData = base64_decode($encodedData);
?>

The data URI you have in your example is not a valid PNG image. This will never work and is unrelated to the code, it's related to the data.


Does not apply but might be of interest:

file_put_contents($_POST['logoFilename'], file_get_contents($data));

The idea behind: PHP itself can read the contents of data URIs (data://) so you don't need to decode it on your own.

Note that the official data URI scheme (ref: The "data" URL scheme RFC 2397) does not include a double slash ("//") after the colon (":"). PHP supports with or without the two slashes.

 # RFC 2397 conform
 $binary = file_get_contents($uri);

 # with two slashes
 $uriPhp = 'data://' . substr($uri, 5);
 $binary = file_get_contents($uriPhp);

The all code that works :

$imgData = str_replace(' ','+',$_POST['image']);
$imgData =  substr($imgData,strpos($imgData,",")+1);
$imgData = base64_decode($imgData);
// Path where the image is going to be saved
$filePath = $_SERVER['DOCUMENT_ROOT']. '/ima/temp2.png';
// Write $imgData into the image file
$file = fopen($filePath, 'w');
fwrite($file, $imgData);
fclose($file);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!