How to upload base64 image in folder php?

In this tutorial, we will let you know how to handle the image encoded with Base64 and write the image to folder. 
While we have working with API for mobile or web application , 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 image to server as a image file.and have to save it in the folder

Example Core PHP:

 

Upload base64 to file in Codeigniter 

Are you looking for a way to save a PNG image server-side, from a base64 data string, or unable to upload to a base64 encoded image using Codeigniter? We can help you with that.

We are creating some function for using base64 string check is valid or not and size and file type

create file application/libraries/Base64fileUploads.php

is_base64($base64string) == true 
        ){  
            $base64string = "data:image/jpeg;base64,".$base64string;
            $this->check_size($base64string);
            $this->check_dir($path);
            $this->check_file_type($base64string);
            
            /*=================uploads=================*/
            list($type, $base64string) = explode(';', $base64string);
            list(,$extension)          = explode('/',$type);
            list(,$base64string)       = explode(',', $base64string);
            $fileName                  = uniqid().date('Y_m_d').'.'.$extension;
            $base64string              = base64_decode($base64string);
            file_put_contents($path.$fileName, $base64string);
            return array('status' =>true,'message' =>'successfully upload !','file_name'=>$fileName,'with_path'=>$path.$fileName);
        }else{
            print_r(json_encode(array('status' =>false,'message' => 'This Base64 String not allowed !')));exit;
        }
    }
    
    public function check_size($base64string){
        $file_size = 8000000;
        $size = @getimagesize($base64string);
        
        if($size['bits'] >= $file_size){
            print_r(json_encode(array('status' =>false,'message' => 'file size not allowed !')));exit;
        }
        return true;
    }
    
    public function check_dir($path){
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
            return true;
        }
        return true;
    }
    
    public function check_file_type($base64string){
        $mime_type = @mime_content_type($base64string);
        $allowed_file_types = ['image/png', 'image/jpeg', 'application/pdf'];
        if (! in_array($mime_type, $allowed_file_types)) {
            // File type is NOT allowed
           // print_r(json_encode(array('status' =>false,'message' => 'File type is NOT allowed !')));exit;
        }
        return true;
    }
}

Example Codeigniter :

Call this class Codeigniter in controller 


$base64file   = new Base64fileUploads();
$return = $base64file->du_uploads($this->data['document'],$document_front_site);

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

How convert Base64 to image and save to folder in PHP?

You shouldn't have to; Base64 images can be loaded directly inside of an tag. If the value is getting stored in the database Base64-encoded, simply load it as you would any other image (making sure to include the Base64 prefix). If you really want to convert back, you can use base64_decode() .

How do I insert an image into Base64?

First convert your image to Base64 (encode to Base64). You can do it online or with a PHP script. Now it's simple to use. You have to just put it in the src of the image and define it there as it is in Base64-encoded form.

How can I download Base64 image in PHP?

header('Content-Disposition: attachment;filename="test. png"'); header('Content-Type: application/force-download'); echo base64_decode($base64strImg);

How do I save an image as a PNG?

Click on the "Save as type" drop-down menu under the File Name field to view all the compatible formats the image can be saved as. Select "PNG" then click "Save." The file will be saved in the same directory as the original one but as a PNG file.