How to create and save image to a website folder from a base64 encoded data/string using PHP

▼魔方 西西 提交于 2020-02-08 10:36:10

问题


I have the following code on my php file which is working fine, Its decoding a base64 string and showing that as a image on the webpage, but i want it to save it on a folder too.

<?php
$base = $_POST['encoded'];
$base = base64_decode($base);

$im = imagecreatefromstring($base);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}
?>

i have already tried the solution described on these links but none of these are worked for me

How to save a PNG image server-side, from a base64 data string

How to create GD Image from base64 encoded jpeg?

what will be the extra line of code which could save this image to a folder


回答1:


$base = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
       .'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
       .'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
       .'8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$base = base64_decode($base);

$im = imagecreatefromstring($base);
if ($im !== false) {
    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
}
else {
    echo 'An error occurred.';
}

Well the code worked for me.
If you see a blank page, that means the string encoded was incorrect.




回答2:


The file permissions was not set to writing mode. set it to 777 and tested with the following code.

<?php
$base = $_POST['encoded'];
$base = base64_decode($base);

$im = imagecreatefromstring($base);
if ($im !== false) {
    header('Content-Type: image/png');

    imagepng($im,'image.png'); // saving image to the same directory

    imagedestroy($im);

}
else {
    echo 'An error occurred.';
}
?>



回答3:


This code works for JPEG image

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHB'; // image data 

define('UPLOAD_DIR','dir_path/'); // image dir path

list($type, $data) = explode(';', $data); 

list(, $data)      = explode(',', $data);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data); // base 64 decoding 

file_put_contents(UPLOAD_DIR.$img_name.".jpeg", $data); // saving the image to required path


来源:https://stackoverflow.com/questions/27416874/how-to-create-and-save-image-to-a-website-folder-from-a-base64-encoded-data-stri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!