"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Resolve Corrupted Image Issues When Converting Data-URI to File in PHP?

How to Resolve Corrupted Image Issues When Converting Data-URI to File in PHP?

Published on 2024-11-09
Browse:470

How to Resolve Corrupted Image Issues When Converting Data-URI to File in PHP?

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.

Release Statement This article is reprinted at: 1729644498 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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