print BASE64 coded image into a FPDF document

前端 未结 7 1805
我寻月下人不归
我寻月下人不归 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:23

    Simply extend Fpdf (tested on 1.8.1) with this function:

    protected function _parsepngdata($data) {
        $f = tmpfile();
        fwrite($f, base64_decode(substr($data, strpos($data,",")+1)));
        fseek($f, 0);
        $info = $this->_parsepngstream($f,"pngdata");
        fclose($f);
        return $info;
    }
    

    and use it this way: (provide base64 data instead of file name, and set type to "pngdata" instead of "png")

    $pdf->Image("data:image/png;base64,iVBORw0KGgo...", $x, $y, $w, $h, "pngdata");
    

    It will create a tempory file, write / read data to/from and delete it afterwards.

    0 讨论(0)
  • 2021-01-04 13:32

    To ensure the images work with FPDF and to avoid errors, here is a modified version of @pedro-soares' code:

    function getImage($dataURI){
      $img = explode(',',$dataURI,2);
      $pic = 'data://text/plain;base64,'.$img[1];
      $type = explode("/", explode(':', substr($dataURI, 0, strpos($dataURI, ';')))[1])[1]; // get the image type
      if ($type=="png"||$type=="jpeg"||$type=="gif") return array($pic, $type);
      return false;
    }
    

    Because FPDF only allows these three file types, it is important to check that it is valid. To use:

    $pic = getImage($Base64StringGoesHere);
    if ($pic!==false) $pdf->Image($pic[0], 10,30,0,0, $pic[1]);
    
    0 讨论(0)
  • 2021-01-04 13:37

    Ok, I wasted half day making test with this issue. I have to tell that this solution is for print images from db row, directly, without stored them on temp files.

    I´m going to write some points to consider:

    • I´m using blob type on the DB to store human signature for print on pdf document
    • I´m sending the signature to store to the db by post method, from a canvas node.
    • When I print the string from the db blob, it´s come without the plus character "+" that don´t let me to print correctly the signature. To solve this issue, I make a "str_replace" to remove the blank spaces and insert the plus character.

    Then the only thing that you have to do is:

    $pdf->Image(str_replace(' ','+',$dbRow['blobImage']),160,150,20,10,'png');
    

    If you need , like me, print several images from the db, you have to see if them come or not, because if the image come empty, you´ll have an error.

    I just add this to the last code:

    if( $dbRow['blobImage'] ){
                     $pdf->Image(str_replace(' ','+',$dbRow['blobImage']),160,150,20,10,'png');
                }
    

    NOTE:

    • 160 -> X position of the image
    • 150 -> Y position of the image
    • 20 -> X Scale of the image
    • 10 -> Y Scale of the image
    • 'png' -> The base format of my Base64 Image Type.
    0 讨论(0)
  • 2021-01-04 13:39

    To add a bit more to Mari M answer, I just added few lines to work with any types of images. (as for me FPDF complains if the image is jpeg and I try to load tempimg.png)

    $this->tempImgLoc = 'tempimg';    // Here I just remove the file extension
    $dataPieces = explode(',',$dataURI);
    $encodedImg = $dataPieces[1];
    $decodedImg = base64_decode($encodedImg);
    
    // extract the image type from data:image/png;base64
    $extension = explode('/', $dataPieces[0]);
    $extension = explode(';', $extension[1]);
    
    $this->tempImgLoc .= '.' . $extension[0];
    

    I am sure there is a better way to do that with regular expression, but to be honest, regexp is not my cup of tea...

    0 讨论(0)
  • 2021-01-04 13:39

    New solution with imagecreatefromstring() Summer 2019

    • delete temporary .png if exist
    • create temporary .png file
    • use $pdf->Image (fpdf)

    My Api returns me a Datamatrix of 1234 as Byte Array. The folowing code shows you how to use that Byte Array as Png in Fpdf.

    My $response = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAABJSURBVChTjYwBCgAgCAP9/6dNreVUgg7Gps3EUOfD5Q4Au6YdAGcH8ygyVKrFnhmbc9FL7qRxWRxEkXWW4Q691UsGpZPzt7dEFyY47RMW+x2LAAAAAElFTkSuQmCC"

    $filename = '/lk_Reptool/printing/tmp/tmppng.png';
    
    if (file_exists($filename)) {
        unlink($filename);
    }
    $response = file_get_contents('https://myapi.com/TwoDCode/GetDatamatrixAsPngByteArray?datamatrixText=' . $RepID . '&pixelSize=100');
    $response = base64_decode($response);
    $img = imagecreatefromstring($response);
    imagepng($img, $filename);
    

    code for pdf

    $pdf = new PDF('P', 'mm', 'A4');
    $pdf->AddPage();
    $pdf->Image('/lk_Reptool/printing/tmp/tmppng.png', 180, 20, 10, 10);
    
    0 讨论(0)
  • 2021-01-04 13:43

    I'know this is an old topic, but there is a easier way of solving this problem. Just try this simple steps:

    1. Strip data:image/png;base64 from URI using explode
    2. Concatenate data://text/plain;base64, with what is left from the stripped URI
    3. Use the result string(base64) as argument of FPDF Image()

    Example:

    $dataURI= "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAMAAADarb8dAAAABlBMVEUAAADtHCTeKUOwAAAAF0lEQVR4AWOgAWBE4zISkMbDZQRyaQkABl4ADHmgWUYAAAAASUVORK5CYII=";
    
    $img = explode(',',$logo,2);
    $pic = 'data://text/plain;base64,'. $img;
    
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->Image($pic, 10,30,0,0,'png');
    $pdf->Output();
    

    Remember of choose the correct image type on Image() function.

    0 讨论(0)
提交回复
热议问题