Last active
February 16, 2023 16:13
-
-
Save lidocaine/c446b89b4f7c8de6e28d400e02595fea to your computer and use it in GitHub Desktop.
Simple function to convert a base64 image string to its original format. Should only be used with trusted data!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function base64_to_image( string $base64_string, string $output_filename = '', string $output_dir = '_base64-out' ): string|false | |
{ | |
$data = explode( ',', $base64_string ); | |
$mime = substr( explode( ';', $data[0] )[0], 5 ); | |
$ext = explode( '/', $mime )[1]; | |
if ( ! str_starts_with( $mime, 'image' ) ) | |
throw new InvalidArgumentException( 'Invalid image mime type data.' ); | |
$output_file = ( empty( $output_filename ) ) | |
? $output_dir . '/base64-' . time() | |
: $output_dir . '/' . $output_filename; | |
$output_file .= '.' . $ext; | |
if ( false !== file_put_contents( $output_file, base64_decode( $data[1] ) ) ) | |
return $output_file; | |
else return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment