PHP tutorial: Converting images into Base 64.

This is a short PHP tutorial on how to convert an image file into Base 64 before displaying it.

Lets take a look at the following example, in which we convert a PNG file into Base 64 before displaying it inline in an img element:

//The file path to our image.
$imagePath = 'image.png';

//Get the extension of the file using the pathinfo function.
$extension = pathinfo($imagePath, PATHINFO_EXTENSION);

//Get the file data.
$data = file_get_contents($imagePath);

//Encode the data into Base 64 using the base64_encode function.
$dataEncoded = base64_encode($data);

//Construct our base64 string.
$base64Str = 'data:image/' . $extension . ';base64,' . $dataEncoded;

?>
<img src="<?= $base64Str; ?>" />

An explanation of the code above:

  1. We declared the path to our image file. In this case, the image is a PNG file. However, it shouldn’t really matter if the image is a PNG, JPEG or GIF because we will automatically figure that out in the next step.
  2. We use PHP’s pathinfo function to get the extension of the file. In the example above, pathinfo returns the string “png“. If our image was “test.jpg”, then this function would have returned “jpg“.
  3. We get the data of the file using file_get_contents. This function reads the data of our file into a string called $data.
  4. We convert the data into Base 64 by using PHP’s base64_encode function.
  5. We created a string that we can insert into the src attribute of our html tag. Note how we used the extension information from Step 2.
  6. Finally, we displayed the image.

If you run the above code and view the src element of the img tag, you should see a rather lengthy Base 64 encoded string.