print BASE64 coded image into a FPDF document

前端 未结 7 1806
我寻月下人不归
我寻月下人不归 2021-01-04 13:03

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

<         


        
相关标签:
7条回答
  • 2021-01-04 13:45

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题