Reputation: 86
I have been trying to convert a base64 string to image file using different methods for the past two days but every time the output file shows no image (it does show size and some encoded data).
Notes: 1. The browser interpreting the file as document and not image mime but I'm pretty sure this is not the problem as I tried to download the file localy and it is the same result. 2. I tried to compare the output results of online tools as codebeautify.org/base64-to-image-converter as it seems the data in the image file is different from my data. 3. Directory and files have 775 permissions and apache have chown
Base64 string here: https://dpaste.de/gP7D/raw
Method A:
list($type, $profile_image) = explode(';', $profile_image);
list(,$extension) = explode('/',$type);
list(,$profile_image) = explode(',', $profile_image);
if($extension == 'jpeg'){$extension = "jpg";}
$filePath = '../uploads/profile_images/'.$uname.'.'.$extension; // using uname instead of unique id to not expose the uqniue key/session
$profile_image = base64_decode($profile_image);
file_put_contents($filePath, $profile_image);
Method B:
list($type, $profile_image) = explode(';', $profile_image);
list(,$extension) = explode('/',$type);
list(,$profile_image) = explode(',', $profile_image);
$filePath = '../uploads/profile_images/'.$uname.'.'.$extension;
$ifp = fopen($filePath, 'wb');
fwrite($ifp, base64_decode($profile_image));
fclose($ifp);
What I'm doing wrong?
Update: Apparently, Apache/php.ini had a maximum max_input_vars of 5000 while my base64 string were much higher. This post can be marked as resolved.
Upvotes: 0
Views: 2167
Reputation: 86
Apache/Php.ini file had a maximum max_input_vars of 5000 while my base64 string were much higher.
Upvotes: 1
Reputation: 998
Seems that you have to remove the begining of your base64 encoded string, that isn't part of the base64 encoded data.
Remove the "data:image/jpeg;base64"
from your base64 string.
I did some simple tests and got the image...
Upvotes: 2