PHP Data-URI to File: Corrupted Images
In web development, it's common to encounter situations where data is received from JavaScript as a Data-URI. One such scenario involves saving this URI to a file using PHP. However, some users have reported receiving corrupt image files after attempting this using the following code:
<code class="php">$data = $_POST['logoImage']; $uri = substr($data,strpos($data,",")+1); file_put_contents($_POST['logoFilename'], base64_decode($uri));</code>
This issue stems from the fact that certain JavaScript functions, such as canvas.toDataURL(), encode blanks as percentages (%). However, the PHP base64_decode function expects plus signs ( ).
To resolve this problem, the code must be modified to replace all blanks with plus signs before decoding the data-URI:
<code class="php">// Replace spaces with pluses $encodedData = str_replace(' ','+',$data); // Decode the modified data-URI $uri = substr($encodedData,strpos($encodedData,",")+1); // Save the decoded data-URI as a file file_put_contents($_POST['logoFilename'], base64_decode($uri));</code>
By implementing this modification, the code will correctly decode and save Data-URIs received from JavaScript, resulting in intact image files.
The above is the detailed content of How to Fix Corrupted Images When Converting Data-URIs to Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!