print BASE64 coded image into a FPDF document

Thomas1703 picture Thomas1703 · Aug 28, 2013 · Viewed 20.8k times · Source

I've some as base64 stored images in a database. Is it possible to print those data directly in a PDF document, using FPDF?

Data sctructure of the image

data:image/png;base64,iVBORw0KGgoAAAANSUhEUg7AAAfQAAACWCAYAAAAonXpvAAAfgUlEQVR4Ae2dC9BuVVnHuSN3QaBENA9h5A2IcJxMj8hUkymoQDfClIkmrQZr1EydMqapnKRMc8JmHLBBHadJJaV0lKQDZCmCQiqQ2KERUFARDhcFDpx /33W tznPe/ 3ttaa9/ a2Z9/32Xvt5nvVbl2evtdfee9dtS27bt4mACJmACJm8ACJtBvArv123xbbwImYAImYAImIAJ26K4HJmACJmACJjAAAnboAyhEZ8EETMAETMAE7NBdB0zABEzABExgAATs0AdQiM6CCZiACZiACdihuw6YgAmYgAmYwAAI2KEPoBCdBRMwARMwAROwQ3cdMAETMAETMIEBELBDH0AhOgsmYAImYAImYIfuOmACJm

I think $pdf->imagepng() should be the right function in FPDF.

Answer

Muhammad Abdul-Rahim picture Muhammad Abdul-Rahim · May 14, 2015

While the comments suggested a TCPDF solution, I did want to state that there is a way to do this entirely with FPDF. The thought process is like this:

  1. Strip data:image/png;base64, from the URI using explode
  2. Decode the URI with base64_decode
  3. Save the decoded data to a PNG file with file_put_contents
  4. Generate a PDF and add the PNG file with Image
  5. Delete the PNG file with unlink

Always remember to error check. If the image fails to save to the server you obviously do not want to continue execution. Make sure to always strictly check if the functions return false!

Here is my solution. I used a tiny image for a small URI in this example.

const TEMPIMGLOC = 'tempimg.png';

$dataURI    = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAMAAADarb8dAAAABlBMVEUAAADtHCTeKUOwAAAAF0lEQVR4AWOgAWBE4zISkMbDZQRyaQkABl4ADHmgWUYAAAAASUVORK5CYII=";
$dataPieces = explode(',',$dataURI);
$encodedImg = $dataPieces[1];
$decodedImg = base64_decode($encodedImg);

//  Check if image was properly decoded
if( $decodedImg!==false )
{
    //  Save image to a temporary location
    if( file_put_contents(TEMPIMGLOC,$decodedImg)!==false )
    {
        //  Open new PDF document and print image
        $pdf = new FPDF();
        $pdf->AddPage();
        $pdf->Image(TEMPIMGLOC);
        $pdf->Output();

        //  Delete image from server
        unlink(TEMPIMGLOC);
    }
}