How to convert base64 to image and save it using PHP?


In this tutorial, i will show you how to convert base64 string to image and write it into folder in PHP. i will write simple code for save base64 encoded image to file using php and you can save it png, jpg as you want.

Many times you need to require to convert base64 string to image and save it to folder. If you are work with an API creation then it is very simple to work with base64 string and you need to convert base64 encoded string into image.

Here in this example i write function generateImage() from base64 string. you can simply follow bellow example:

Example:

<?php


generateImage($_POST['image']);


public function generateImage($img)

{

$folderPath = "images/";


$image_parts = explode(";base64,", $img);

$image_type_aux = explode("image/", $image_parts[0]);

$image_type = $image_type_aux[1];

$image_base64 = base64_decode($image_parts[1]);

$file = $folderPath . uniqid() . '.png';


file_put_contents($file, $image_base64);

}


?>

I hope it can help you....






April 3, 2018 | Category : PHP
Related Posts