Base64 to image conversion in php

By | March 30, 2018
base64 to image in php

Hello Guys,

Today i am going to tell you about to base64 to image conversion through php script

sometimes we need to store whole image into our DB then we store in the base64 image format and while getting that image to show on the page we first need to be decode that base64 image.

This situation generally arises while working with api for an app.

In this example you will learn to decode base64 encoded image and save that image into a directory.

Lets assume you have encoded image data into your database and you fetch that data into a variable $encoded_image.

    define('UPLOAD_DIR', 'images/');
    $image_parts = explode(";base64,", $encoded_image);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $file = UPLOAD_DIR . uniqid() . $image_type;
    file_put_contents($file, $image_base64);

in the above code firstly we define upload directly path and give full permission to this directory because we are going to write image file into this directory.

And after that we are breaking the string into arrays to get image and image file type.

After getting the image part simply apply base64_decode function that encoded image part and copy this content into a file.

And after executing this file you will an image will be available into the upload directory. That is the file that you were expecting.

Link price calculator