Home > Backend Development > PHP Tutorial > How to Fix Corrupted Images When Converting Data-URIs to Files in PHP?

How to Fix Corrupted Images When Converting Data-URIs to Files in PHP?

DDD
Release: 2024-10-23 08:52:29
Original
1047 people have browsed it

How to Fix Corrupted Images When Converting Data-URIs to Files in PHP?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template