How to convert an image to Base64 encoding with PHP?

Spread the love

Sometimes, we want to convert an image to Base64 encoding with PHP.

In this article, we’ll look at how to convert an image to Base64 encoding with PHP.

How to convert an image to Base64 encoding with PHP?

To convert an image to Base64 encoding with PHP, we can use the file_get_contents function.

For instance, we write

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

to call pathinfo with the image $path to get the file extension of the image.

Then we call file_get_contents with the $path to return the content of the image.

Next, we build the $base64 string with

'data:image/' . $type . ';base64,' . base64_encode($data);

We put the .type after 'data:image/' and the base64 image that we get from base64_encode($data) at the end of the string.

Conclusion

To convert an image to Base64 encoding with PHP, we can use the file_get_contents function.

Leave a Reply

Your email address will not be published. Required fields are marked *