【问题标题】:How to insert base64 image into fpdf?如何将base64图像插入fpdf?
【发布时间】:2018-12-21 02:34:58
【问题描述】:

我已经看到了各种各样的答案,但无论出于何种原因,我似乎都无法让它们发挥作用。

首先,我从我的数据库中提取文件:

try {
    $getQuery = "SELECT * FROM firstForm WHERE id =:id";
    $statement = $db->prepare($getQuery);
    $statement->execute(array(':id' => 2));

    if($row = $statement->fetch()) {
        $fileName = $row['pic'];
    }
}

当我回显 $fileName 时,它​​会生成“data:image/png;base64...”

如何转换 $fileName 以便在 fpdf 中使用它,如下所示:

$pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
$pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs

$pdf->AddPage();
$pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, align
$pdf->Image($fileName);
$pdf->Output();

【问题讨论】:

标签: php fpdf


【解决方案1】:

尽管正如詹姆斯所建议的那样,print BASE64 coded image into a FPDF document 的答案提供了一个很好的解决方案。在您的情况下,您可以将以下代码保存为image.php,然后将该图像(带有$_GET['id'] 集)添加到pdf 中:$pdf->Image('/image.php?id=2');。在调用image.php之前,请务必检查数据库中是否存在该图像。

<?php
if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) { // Only allow requests from server.
    header($_SERVER["SERVER_PROTOCOL"] . "  791 The Internet shut down due to copyright restrictions", true, 791);
    die();
}

if (empty($_GET['id'])) {
    die('Handle this.');
}

// get your $db object in here.
$getQuery = "SELECT * FROM firstForm WHERE id =:id";
$statement = $db->prepare($getQuery);
$statement->execute(array(':id' => 2));

if ($row = $statement->fetch()) {
    $data = $row['pic'];
} else {
    // This shouldn't happening, you should be checking whether firstForm with the id you're calling the image for exists.
}

$exploded = explode(';', $data);
$mimetype = substr($exploded[0], 5);
$data = explode(',', $exploded[1])[1];

header('Content-type: ' . $mimetype);
echo base64_decode($data);

你的 pdf 创建看起来像这样:

$pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
$pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs

$pdf->AddPage();
$pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, align
$pdf->Image('/image.php?id=2');
$pdf->Output();

【讨论】:

  • 我正在使用cropit来保存图像,但我不知道如何让cropit添加一个id。我也看不出有一个 id 有什么关系。我知道如何获取数据。我不知道如何使用 fpdf 中的数据。我尝试使用您提到的解决方案中的答案,但无法让其中任何一个起作用。
  • @Colin 编辑我的答案有帮助吗?如果没有,我很乐意进一步解释。
  • @Colin 添加了 pdf 创建外观的示例
【解决方案2】:

所以,我想通了。答案就在这个 SO 答案print BASE64 coded image into a FPDF document 中,它有效。

问题在于图像是如何存储在数据库中的。当出于某种原因需要将其存储为 LONGBLOG 时,我将其存储为 BLOB。

感谢您尝试@Nielles。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2022-11-07
    • 2019-08-05
    • 2016-01-11
    • 1970-01-01
    相关资源
    最近更新 更多