Home » How To Convert Base64 To Image In PHP

How To Convert Base64 To Image In PHP

Last updated on December 30, 2020 by

Generally, API development requires to convert Base64 to Image in PHP. Nowadays, PHP is one of the most popular backend options for Mobile. So it is a very common requirement to save images from Mobile to its backend. Let’s jump into it.

How to Save Images through API?

Most of the Mobile applications use PHP as a backend. So whenever any request made from the Mobile, it triggers the PHP API like Login, Registration, Data Manipulations, and much more.

Sometimes, It is required to upload an image through Mobile application to its backend so Mobile sends the Image as Base64 code to its backend. Let’s save that now.

Notes: It is advisable not to save base64 code into the database. Instead, that just saves the path of the uploaded image to the database. Storing base64 code into the database will cause huge performance issue and it will eat your huge database storage space.

Convert Base64 to Image in PHP

<?php 

/*@ Base64 image code */
$data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6BAMAAAB6wkcOAAAAG1BMVEX///8AAACfn59fX18fHx/f39+/v79/f38/Pz9KdSATAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACeklEQVR4nO3WQU8aQRTA8WFxdj26uiw9QqIJR5vaxmPRJnBcWmuvSxNJj9gYy1G0rX7svjc7W5YApu1yav6/hOU5vMzbN8wsGgMAAAAAAAAAAAAAAAAAAAAAAAAAAPA/CE7i80zee0+iI0H0PXnzTF6gefc6Muuf5zWLh8nXSW9fgtNvQmaz724/z6eb85qPkncrwcVg0mvXrd6Ry7VUffADOz+kv/3NebvHfmQoK9Ht1CzvKsqMjz6+1uU92Zy369clasml+XYL1SOZZOBj9z7qbMzb8dXdu11dpH+rflaEYarXYnlt7kay5er+xsbuwwdTn87quwj2ygGJ3Z2Mp0t5DV+96643W6iuraZ2ok1Gd4t7cLssbC/nNfLLK41nlXuoR1bRtudxIl02XfWw5cajdKl1t9qjWRzr3jgtRjJT25N8x8mReT+U6seV6tJ8tXXNM6OzzB7KLb7aVvVAa+Xyupj6/VZWj9Jq6y4vlJcdlPttC9XHHR/IrlpaeWm+vS5PN9u2Vt6el5EU9dX3yoLpujwt6qvXLW4uymensak/a8VVN7xu+5U8M8r9Wat94uxwEbb8mhcroBs+StfkmVHm1/y0bvVKS3rM3VPHP051w/9uvpKnx7zR0WBg6gkX36Zr2f3AdIvNpBu+bL6apy27H5igZeqpHqluLosqf9tipxdn3Te/dPRSnzNa/UfgrwQHH0VmgvvMfNAJw4PMHN4V1d3cUV7NM70jY1/qB+PXJhiun/SP7caqZexN3H/h6nyJ+2u+zTLPfOon8U93b/Mkqdl6xeWkDK6ezbOTvAy28JAHAAAAAAAAAAAAAAAAAAAAAAAAAAArfgEnYGI6+pXm3AAAAABJRU5ErkJggg==";

function tf_convert_base64_to_image( $base64_code, $path, $image_name = null ) {
	
	if ( !empty($base64_code) && !empty($path) ) :

		// split the string to get extension and remove not required part
	    // $string_pieces[0] = to get image extension
	    // $string_pieces[1] = actual string to convert into image
		$string_pieces = explode( ";base64,", $base64_code);

		/*@ Get type of image ex. png, jpg, etc. */
		// $image_type[1] will return type
		$image_type_pieces = explode( "image/", $string_pieces[0] );

		$image_type = $image_type_pieces[1];

		/*@ Create full path with image name and extension */
		$store_at = $path.md5(uniqid()).'.'.$image_type;

		/*@ If image name available then use that  */
		if ( !empty($image_name) ) :
			$store_at = $path.$image_name.'.'.$image_type;
		endif;

		$decoded_string = base64_decode( $string_pieces[1] );

		file_put_contents( $store_at, $decoded_string );

	endif;

}

// Calling function auto generate unique name
tf_convert_base64_to_image( $data, 'assets/images/' );

// Calling function with predefined image name
tf_convert_base64_to_image( $data, 'assets/images/', 'my-image' );

We have already explained most of the code in a comment. The above code will save 2 images in path your-project-folder/assets/images. One image will be saved with an auto-generated unique name and another one will be saved with ‘my-image’ name. If you run the above code, then you should get images like the below screenshot.

Save Images through API in PHP

Very Quick Alternate Solution

<?php 

$data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6BAMAAAB6wkcOAAAAG1BMVEX///8AAACfn59fX18fHx/f39+/v79/f38/Pz9KdSATAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACeklEQVR4nO3WQU8aQRTA8WFxdj26uiw9QqIJR5vaxmPRJnBcWmuvSxNJj9gYy1G0rX7svjc7W5YApu1yav6/hOU5vMzbN8wsGgMAAAAAAAAAAAAAAAAAAAAAAAAAAPA/CE7i80zee0+iI0H0PXnzTF6gefc6Muuf5zWLh8nXSW9fgtNvQmaz724/z6eb85qPkncrwcVg0mvXrd6Ry7VUffADOz+kv/3NebvHfmQoK9Ht1CzvKsqMjz6+1uU92Zy369clasml+XYL1SOZZOBj9z7qbMzb8dXdu11dpH+rflaEYarXYnlt7kay5er+xsbuwwdTn87quwj2ygGJ3Z2Mp0t5DV+96643W6iuraZ2ok1Gd4t7cLssbC/nNfLLK41nlXuoR1bRtudxIl02XfWw5cajdKl1t9qjWRzr3jgtRjJT25N8x8mReT+U6seV6tJ8tXXNM6OzzB7KLb7aVvVAa+Xyupj6/VZWj9Jq6y4vlJcdlPttC9XHHR/IrlpaeWm+vS5PN9u2Vt6el5EU9dX3yoLpujwt6qvXLW4uymensak/a8VVN7xu+5U8M8r9Wat94uxwEbb8mhcroBs+StfkmVHm1/y0bvVKS3rM3VPHP051w/9uvpKnx7zR0WBg6gkX36Zr2f3AdIvNpBu+bL6apy27H5igZeqpHqluLosqf9tipxdn3Te/dPRSnzNa/UfgrwQHH0VmgvvMfNAJw4PMHN4V1d3cUV7NM70jY1/qB+PXJhiun/SP7caqZexN3H/h6nyJ+2u+zTLPfOon8U93b/Mkqdl6xeWkDK6ezbOTvAy28JAHAAAAAAAAAAAAAAAAAAAAAAAAAAArfgEnYGI6+pXm3AAAAABJRU5ErkJggg==";

file_put_contents('assets/images/my-quick-file.jpg', file_get_contents($data));

Additionally, read our guide:

  1. How to Select Data Between Two Dates in MySQL
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. Check If A String Contains A Specific Word In PHP
  12. Dynamically Populate A Select Field’s Choices In ACF
  13. How To Find Duplicate Records in Database
  14. How To Create Dynamic Variable In PHP

That’s it from our end. We hope this article helped you to learn How to Convert Base64 to Image in PHP.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment