Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve image from public folder and convert to base64 in Laravel?

I want to get the image file from my public folder which I stored all of my images, then convert to base64. I will use the base64 image to view it on PDF using pdfmake in dataTables, because my dataTable cell have an Image called avatar, and as I've searched it needs to convert image to base64 to able to view in PDF.

Now I use file_get_contents to retrieve my image, but my page is too much load I guess it's around 5mins, and after throws and error Maximum execution time of 60 seconds exceeded.

{{ file_get_contents( asset('files/user_avatar.png') ) }}
like image 955
Jin Avatar asked Oct 16 '25 05:10

Jin


1 Answers

There is difference between svg and (jpg-png-jpeg) when you encoding to base64. You can use basically png extension when you working with png image. But you cant use svg basically. You need svg+xml when you working with svg.

function img_enc_base64 ($filepath){   // img_enc_base64() is manual function you can change the name what you want.

    if (file_exists($filepath)){

        $filetype = pathinfo($filepath, PATHINFO_EXTENSION);

        if ($filetype==='svg'){
            $filetype .= '+xml';
        }

        $get_img = file_get_contents($filepath);
        return 'data:image/' . $filetype . ';base64,' . base64_encode($get_img );
    }
}

so now

echo img_enc_base64('file_path');  // is your base64 code of image

<img src="<?php echo img_enc_base64('file_path');?>" alt="">  // is your image

file_path example: pics/my_book.png

like image 95
Sha'an Avatar answered Oct 17 '25 21:10

Sha'an



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!