When you are handling API for apps ( iPhone, android, etc ), you can see that they provides the image in Base64 encoded format mostly, so we need to save base64 encoded image to server as a image file. This tutorial will let you know how to save Base64 encoded image to server as a image file using PHP.
If you are getting the image data with image type like as below:
$data = $_POST['image']; $data = 'data:image/png;base64,AFFAAFdsgBLKLKS346fj42Pj4...';
You need to parse base64 part from this image data like below:
$data = str_replace('data:image/png;base64,', '', $data); $data = str_replace(' ', '+', $data);
Now decode the image data using base64_decode function like below:
$data = base64_decode($data);
Now you can put this image data to your desired file using file_put_contents function like below:
$file = 'images/'. uniqid() . '.png'; $success = file_put_contents($file, $data);
If you want to rotate the image and save you can use following code:
$data = base64_decode($data); // base64 decoded image data $source_img = imagecreatefromstring($data); $rotated_img = imagerotate($source_img, 90, 0); // rotate with angle 90 here $file = 'images/'. uniqid() . '.png'; $imageSave = imagejpeg($rotated_img, $file, 10); imagedestroy($source_img);
This is a simple program to save Base64 encoded image to server file using PHP. Hope this tutorial will help you.