Search code examples
phpimagebase64fpdfdata-uri

Convert Image Data URI to Image PHP


I have a data uri variable in php

$imageURL  = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAYAAACadoJwAAAgAElEQ…ACIiACIiAC5U1AAqS891erEwEREAEREAEREAEREIFAEfj/bfXX..."

I am trying to insert this into a pdf using fpdf for which I need to convert this into a image I guess. I tried doing something like

base64_decode($imageURL);

but this does not work. How I successfully insert this data uri into pdf.


Solution

  • $image_content = base64_decode(str_replace("data:image/png;base64,","",$imageURL)); // remove "data:image/png;base64,"
    $tempfile = tmpfile(); // create temporary file
    fwrite($tempfile, $image_content); // fill data to temporary file
    $metaDatas = stream_get_meta_data($tempfile);
    $tmpFilename = $metaDatas['uri'];
    

    Now you can use that image into fpdf like:

    $pdf->Image($tmpFilename,null,null,0,0);
    

    Or you can specify image type by adding image type parameter like this:

    $pdf->Image($tmpFilename,null,null,0,0,'PNG');
    

    Please check to http://www.fpdf.org/en/doc/image.htm