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

Susan Sarandon
Release: 2024-10-23 08:48:29
Original
753 people have browsed it

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:

<code class="php">$encodedData = str_replace(' ', '+', $encodedData);
$decodedData = base64_decode($encodedData);</code>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!