duanfan8360 2015-11-10 12:58
浏览 200
已采纳

使用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 13: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 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题