duanfan8360 2015-11-10 04:58
浏览 202
已采纳

使用FPDF将数据库中的图像转换为PDF

I have an image that is sent from an iPad app to an SQL database. I can retrieve this image and display in a web page using the following php:

$img = base64_encode($row['photoData']);
echo "<img src=\"data:image/jpg;charset=utf8;base64, $img\"/>";

This displays fine. What I want to do now is put this image into a PDF document using FPDF however I am struggling to do this.

This:

$img = base64_encode($row['photoData']);
$pdf->Image($img);

give this error:

FPDF error: Image file has no extension and no type was specified:

So I tried this (although I realise I will then have to look at how to get the size of the image sorted):

$pdf->Image($img, 20, 20, 20, 20 'JPG');

which give me:

FPDF error: Missing or incorrect image file:

What is the correct way to do this?

Or would it be easier to temporarily save the image to the server and then place the saved image into the PDFdoc?

  • 写回答

4条回答 默认 最新

  • dongxi1943 2015-11-10 05:30
    关注

    Since FPDF cannot use base64 data to produce images on the PDF, I would recommend saving the file to the disk permanently as opposed to writing a temp file for every PDF operation.

    This will save you a lot of I/O overhead.


    Assuming your table has unique photo_id or photo_name to accompany photoData then you can use something like this to create your images and use them in FPDF.

    I will also assume you have a last_update and photo_extension column.

    <?php
    
    $path = '/path/to/fpdf/images/';
    
    $filename = $row['photo_id'].'.'.$row['photo_extension'];
    
    $filepath = $path.$filename;
    
    // If a physical file is not available then create it
    // If the DB data is fresher than the file then make a new file
    if(!is_file($filepath) || strtotime($row['last_update']) > filemtime($filepath))
    {
        $result = file_put_contents($filepath, $row['photoData']);
    
        if($result === FALSE)
        {
            die(__FILE__.'<br>Error - Line #'.__LINE__.': Could not create '.$filepath);
        }
    }
    
    $pdf->Image($filepath);
    

    If you plan on updating the photoData which is stored in your DB then you will have to make sure to also have a timestamp column and compare that timestamp against the filemtime($filepath) of the image on your disk.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 Codesys配置ethercat错误
  • ¥15 mstsc远程桌面轮流掉线
  • ¥15 求一下oivio数据集
  • ¥15 android开发百度网盘文件浏览功能,是什么做的?用的什么技术实现?
  • ¥20 地震波形数据向量化的问题
  • ¥15 脊柱MRI图片分割与自动识别
  • ¥50 使用ADC0809 与 51 单片机设计电路以实现显示电压模拟值
  • ¥15 QGC打开没有地图显示,离线地图也不显示,如何解决?
  • ¥20 Android Studio 的 webview 与访问网络存在的限制
  • ¥15 某帖子的数据集不清楚来源,求帮助