Badal Surana Badal Surana - 1 year ago 198
PHP Question

Convert Base64 string to an image file?

I am trying to convert my base64 image string to an image file. This is my Base64 string:

Using following code to convert it into an image file:

function base64_to_jpeg( $base64_string, $output_file ) {
$ifp = fopen( $output_file, "wb" );
fwrite( $ifp, base64_decode( $base64_string) );
fclose( $ifp );
return( $output_file );

$image = base64_to_jpeg( $my_base64_string, 'tmp.jpg' );

But I am getting an error of
invalid image
, whats wrong here?

Answer Source

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
    $ifp = fopen($output_file, "wb"); 

    $data = explode(',', $base64_string);

    fwrite($ifp, base64_decode($data[1])); 

    return $output_file; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download