PHP Convert Base64-Encoded Image to File

Posted on July 23, 2019 at 9:10 am

Simple function to convert a base64-encoded image to an image file:

function base64_to_image($base64_string, $output_file) 
{
    $file_handle = fopen($output_file, 'wb');
 
    if(!$file_handle) return array("status" => "error", "message" => "Failed to create output file");
 
    $image_types = array("data:image/png;base64,", "data:image/jpeg;base64,", "data:image/jpg;base64,", "data:image/bmp;base64,", "data:image/svg+xml;base64,", "data:image/x-icon;base64,");
 
    $base64_string = str_replace($image_types, '', $base64_string);
 
    $base64_decoded = base64_decode($base64_string);
 
    if(!$base64_decoded) return array("status" => "error", "message" => "Failed to decode base64 string");
 
    fwrite($file_handle, $base64_decoded);
 
    fclose($file_handle); 
 
    return array("status" => "success", "file" => $output_file); 
}

It supports converting of base64 image to PNG, JPEG, JPG, BMP, GIF, ICO, SVG file.

The usage is simple, here is an example:

$image = base64_to_image(ENTER_BASE64_ENCODED_STRING, "image.png");
 
if($image['status'] == "success")
{
    echo '<img src="'.$image['file'].'" />';
}
else
{
    echo "Error: ".$image['message'];
}

Need to convert an image file to base64? Read this:

PHP Convert an Image File to Base64

Updated on July 26, 2019 at 10:51 am

Receive updates via email

Other Posts

Updated Posts