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:
$encodedData = str_replace(' ', ' ', $encodedData);
$decodedData = base64_decode($encodedData);
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:
// 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);
By following this approach, you can successfully save the Data-URI as a non-corrupted PNG file.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3