Skip to content

Instantly share code, notes, and snippets.

@lidocaine
Last active February 16, 2023 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidocaine/c446b89b4f7c8de6e28d400e02595fea to your computer and use it in GitHub Desktop.
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!
<?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