将 BASE64 编码图像打印到 FPDF 文档中
我在数据库中有一些作为 base64 存储的图像.是否可以使用 FPDF 直接在 PDF 文档中打印这些数据?
I've some as base64 stored images in a database. Is it possible to print those data directly in a PDF document, using FPDF?
图像的数据结构
<代码>数据:图像/PNG; BASE64,iVBORw0KGgoAAAANSUhEUg7AAAfQAAACWCAYAAAAonXpvAAAfgUlEQVR4Ae2dC9BuVVnHuSN3QaBENA9h5A2IcJxMj8hUkymoQDfClIkmrQZr1EydMqapnKRMc8JmHLBBHadJJaV0lKQDZCmCQiqQ2KERUFARDhcFDpx/33W tznPe/3ttaa9/a2Z9/32Xvt5nvVbl2evtdfee9dtS27bt4mACJmACJm8ACJtBvArv123xbbwImYAImYAImIAJ26K4HJmACJmACJjAAAnboAyhEZ8EETMAETMAE7NBdB0zABEzABExgAATs0AdQiM6CCZiACZiACdihuw6YgAmYgAmYwAAI2KEPoBCdBRMwARMwAROwQ3cdMAETMAETMIEBELBDH0AhOgsmYAImYAImYIfuOmACJm
我认为 $pdf->imagepng()
应该是 FPDF 中的正确函数.
I think $pdf->imagepng()
should be the right function in FPDF.
推荐答案
虽然评论建议使用 TCPDF 解决方案,但我确实想说明有一种方法可以完全使用 FPDF.思考过程是这样的:
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:
- 使用
explode
data:image/png;base64,> - 使用
base64_decode
解码 URI - 使用
file_put_contents
将解码后的数据保存到 PNG 文件中一个> - 生成 PDF 并添加带有
Image
的 PNG 文件李> - 使用
unlink
删除 PNG 文件
- Strip
data:image/png;base64,
from the URI usingexplode
- Decode the URI with
base64_decode
- Save the decoded data to a PNG file with
file_put_contents
- Generate a PDF and add the PNG file with
Image
- Delete the PNG file with
unlink
永远记得错误检查.如果图像无法保存到服务器,您显然不想继续执行.确保始终严格检查函数是否返回 false!
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!
这是我的解决方案.在这个例子中,我使用了一个小图片作为一个小 URI.
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);
}
}
相关文章