Convert base64 to image file in 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.
1 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?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.
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!
not working
Hi Advert,
Make sure you have an
images
directory with permission before executing the code.i’m success for save my image to my local, but my problem is i want to send the image from my local to another API services. can you help me to solve my problem? 🙁
Hi Vito,
You can convert your image to the base64 encoded string and pass it to the API or you have to pass your image in form of the “multipart/form-data” (FormData) in the API services.