You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决FPDF展示MSSQL图片列PNG图片时的报错问题?

Fixing FPDF PNG Image Error with MSSQL Image Field

Got it, let's tackle this issue head-on. The problem with your current code is two-fold: you're hardcoding the image format as jpg in the Image() call, and using a generic text/plain MIME type in your data URI—neither works when dealing with PNG files. Here's how to fix it:

Step 1: Dynamically Detect Image Format

First, we need to figure out whether the binary data from your MSSQL image field is a JPG or PNG (you can extend this for other formats later if needed). We can do this by checking the file header signatures:

  • JPG files start with the hex bytes FF D8
  • PNG files start with 89 50 4E 47 (which translates to ‰PNG in ASCII)

Step 2: Generate Correct Data URI & Call FPDF Image

Once we know the format, we can set the right MIME type for the data URI and pass the correct format to FPDF's Image() method. Here's the revised code:

// Clean and convert the MSSQL image field data to binary
$cleanHex = preg_replace("/[^0-9a-f]+/i", "", $srcOBS);
$imageBinary = pack("H*", $cleanHex);

// Detect the image format by checking file headers
$imageType = '';
$mimeType = '';

// Check for JPG signature
if (substr($imageBinary, 0, 2) === "\xFF\xD8") {
    $imageType = 'jpg';
    $mimeType = 'image/jpeg';
} 
// Check for PNG signature
elseif (substr($imageBinary, 0, 4) === "\x89\x50\x4E\x47") {
    $imageType = 'png';
    $mimeType = 'image/png';
} 
// Handle unsupported formats (optional)
else {
    // You can throw an error, log it, or skip the image
    die("Unsupported image format in database field");
}

// Create the properly formatted data URI
$pic = "data:$mimeType;base64," . base64_encode($imageBinary);

// Render the image with the correct format parameter
$pdf->Image($pic, 17, 46, 32.5, 40, $imageType);

Why This Works

  • Dynamic Format Detection: No more forcing JPG on every image—FPDF will use the correct parser for each file type.
  • Proper MIME Type: The data URI now tells FPDF exactly what kind of data it's receiving, instead of pretending it's plain text.
  • Robust Data Handling: We first validate the binary data's format before trying to render it, which helps catch corrupted or unsupported files early.

Extra Tips

  • If your database might contain other image formats (like GIF), you can add more signature checks (e.g., GIF starts with 47 49 46 38).
  • To debug, you can temporarily save $imageBinary to a local file (e.g., file_put_contents('test.png', $imageBinary);) to confirm the data from MSSQL is intact and not truncated.

内容的提问来源于stack exchange,提问作者Muhammed Yusuf Taşkesenligil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:51:08