How to convert base64 to image and save in folder php?

Today, We want to share with you convert base64 to image php.In this post we will show you base64 to image conversion through php script, hear for base64 image conversion php we will give you demo and example for implement.In this post, we will learn about Convert base64 to image file and write To folder in PHP with an example.

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

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.

Also Read This 👉   PHP Inline Editing Table using jQuery Ajax

This case generally problem arises while working with php api for an application.

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

PHP - Save base64 Encoded string - Convert base64 to Image
PHP – Save base64 Encoded string – Converts base64 to Image

Lets simple example you have encoded image data into your any mysql database as well as you get that data into a php variable $encoded_image.

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

in the above full source code quickly i define upload directly path as well sa give full folder permission to this File Folders because i am going to write image file into this File Folders.

And after that i am breaking the string into arrays to get image and image file type.

Also Read This 👉   How to Open URL in New Tab using Magento

After getting the image part simply apply php function base64_decode that encoded image part as well as simple copy this data content into a file.

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



    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 you get an idea about convert base64 to image php.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.