How to create and save image to a website folder f

2019-09-10 22:28发布

问题:

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


标签: php image base64