Convert base64 to image file and write To folder in PHP

Convert base64 to image file and write To folder in PHP

In this tutorial, I will let you know how to handle the images encoded with Base64 and write the images to folder.

While working with API for app, You will notice that they will send the format of images in Base64 encoded. So in that case, you will need to move the Base64 encoded images to server as a image file.

In PHP, Its very easy to get image file from Base64 encoded.

While working with canvas, you will have base64 encoded string in the form, then you will send the form data to the server using POST method and on the server, you convert them into an image file.

  1. <?php
  2.     define('UPLOAD_DIR', 'images/');
  3. $image_parts = explode(";base64,", $_POST['image']);
  4.     $image_type_aux = explode("image/", $image_parts[0]);
  5.     $image_type = $image_type_aux[1];
  6.     $image_base64 = base64_decode($image_parts[1]);
  7.     $file = UPLOAD_DIR . uniqid() . '.png';
  8.     file_put_contents($file, $image_base64);
  9. ?>    

Laravel Intervention Summernote Editor to get upload File(image) URL instead of Base64

Phone: (+91) 8800417876
Noida, 201301