Clue Mediator

Convert base64 to image file in PHP

📅April 7, 2020
🗁PHP

Today we will show you how to convert base64 to image file in PHP. In the previous article we learned how to convert an image to base64 encoded string using PHP.

Convert Base64 to image in PHP, Converting images into Base 64, php base64 encoded image from url, php decode base64 image and display, php convert base64 image to jpg, base64 image store in php, Convert base64 to image file and write To folder in PHP, How to convert a base64 image into a image file and save it in directory/folder.

Checkout more articles on PHP

Example to convert base64 to image file

Let’s assume that we’ve the following base64 image string.

iVBORw0K...kSuQmCC

Note: The given base64 image string is not a complete image string so use your base64 image string to execute the code. Check out the git source for the demo string.

Now try to generate an image file using PHP. The following code will help you to do it. Make sure you have an `images` directory with permission before executing the code.

index.php

<?php

// base64 image code
$base64_code = "<YOUR_BASE64_IMAGE_STRING>";

// create an image file
$fp = fopen("./images/clue_mediator.png", "w+");

// write the data in image file
fwrite($fp, base64_decode($base64_code));

// close an open file pointer
fclose($fp);

?>

Let’s try to understand code line by line.

  • First consider the base64 image code to convert it into an image.
  • Use fopen() function to create an image file in the given directory.
  • Now use the fwrite() function to write the base64 image code in an image file.
  • At last we have to close an open file pointer for that we used fclose() function.

After executing the `index.php` file we can get an image from base64 code and save it in the given path of the directory.

That’s it for today.
Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository