PHP Data-URI to File: Resolving Corrupted Image Issues
Maintaining the integrity of image data during conversion from Data-URI to file format is crucial. A common challenge encountered while using PHP's file_put_contents function to save data from a JavaScript canvas.toDataURL() call is corruption of the resulting image. The issue stems from the presence of white spaces in the Data-URI.
PHP's documentation provides a straightforward solution to this problem:
<code class="php">$encodedData = str_replace(' ', '+', $encodedData); $decodedData = base64_decode($encodedData);</code>
By replacing white spaces with plusses, the decoded data is correctly reconstructed, ensuring that the image file is not corrupted.
In your specific case, you were working with a Data-URI containing a PNG image. Here's how you can incorporate the solution into your code:
<code class="php">// Get the base64-encoded URI data from JavaScript $data = $_POST['logoImage']; // Remove the leading "data:image/png;base64," part $uri = substr($data, strpos($data, ',') + 1); // Replace any whitespace with a plus $uri = str_replace(' ', '+', $uri); // Decode the base64-encoded data $decodedData = base64_decode($uri); // Save the decoded data to a file with the specified name file_put_contents($_POST['logoFilename'], $decodedData);</code>
By following this approach, you can successfully save the Data-URI as a non-corrupted PNG file.
The above is the detailed content of How to Resolve Corrupted Image Issues When Converting Data-URI to File in PHP?. For more information, please follow other related articles on the PHP Chinese website!