How to convert an image to base64 encoding in PHP?
The base64_encode() function is an inbuilt function in PHP which is used to convert any data to base64 encoding. In order to convert an image into base64 encoding firstly need to get the contents of file. This can be done with the help of file_get_contents() function of PHP. Then pass this raw data to base64_encode() function to encode.
Required Function:
- base64_encode() Function The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.
- file_get_contents() Function The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.
Input Image:

Program:
<?php // Get the image and convert into string $img = file_get_contents( // Encode the image string data into base64 $data = base64_encode($img); // Display the output echo $data; ?> |
Output:
iVBORw0KGgoAAAANSUhEUgAAApsAAAC4CAYAAACsNSfVAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJ
cEhZcwAADsQAAA7EAZUrDhsAAAAZdEVYdFNvZnR3YXJdhfdsglgklAEFkb2JlIEltYWdlUmVhZHlxyWqwrwtwefd
...
TeUsalQKBQKhUKhsBvK2FQoFAqFQqFQ2A1lbCoUCoVCoVAo7IYyNhUKhUKhUCgUdkMZmwqFQKBQKO0H0fxpZ1bfc
Reference:
- http://php.net/manual/en/function.base64-encode.php
- http://php.net/manual/en/function.file-get-contents.php
Recommended Posts:
- Convert an image into grayscale image using HTML/CSS
- How to convert a PDF document to a preview image in PHP?
- Convert an image into Blur using HTML/CSS
- How to convert an HTML element or document into image ?
- JavaScript | Encode/Decode a string to Base64.
- Getting started with Scikit-image: image processing in Python
- HTML | URL Encoding
- Web TextEncoder API | TextEncoder encoding property
- CSS | Image Sprites
- CSS | Image Gallery
- Saving an Image from URL in PHP
- What is Image Blurring
- HTML | Mapping Image
- Set the size of background image using CSS ?
- Image Steganography in Cryptography
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



