Skip to content
Advertisement

Base64 image string into image file using PHP

I need code to convert a base64 image string into an image file and write into local directory using PHP. I tried:

function user_profile_photo(){
            $input = urldecode(file_get_contents('php://input'));
            $received = json_decode($input, true);
            $user_id = $received['user_id'];
            $img = $received['imagecode'];
            $imagedata = base64_decode($img);
            $image_path='uploads/images/'.$user_id;             
            $path = '/var/www/html/empengapp/uploads/images/'.$user_id;
            if (!file_exists($path)) {
                   mkdir($path, 0755, true);
             }

$new_name = date('ymd').time().'.jpg';
$pathwithfile = '/var/www/html/empengapp/uploads/images/'.$user_id.'/'.$new_name;
$success = file_put_contents($pathwithfile, $imagedata);
var_dump($imagedata);exit;




            $this->output
                ->set_status_header(200)
                ->set_content_type('application/json', 'utf-8')
                ->set_output(json_encode($resp, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
                ->_display();
                exit;
    }//end of function user_profile_photo

It is writing a file with given extension, but when you try to open file it shows an invalid file error.

Advertisement

Answer

I figure it out the solution.

        $pathwithfile = 'your file path with image name';//e.g '/uploads/test.jpg'

         $ifp = fopen( $pathwithfile, 'wb' ); 

			    // split the string on commas
			    // $data[ 0 ] == "data:image/png;base64"
			    // $data[ 1 ] == <actual base64 string>
			    $data = explode( ',', $imagedata );
			    $success = fwrite( $ifp, base64_decode( $data[ 1 ] ) );			    // clean up the file resource
			    fclose( $ifp );
          
          

I was sending over the API to PHP server. You need to encode your image base64 string and your image base64 string must include “data:image/jpeg;base64”. We are splitting it on PHP server But don’t think to send image base54 without “data:image/jpeg;base64”.
But remember one thing you have to use image base64 including

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement