PHP 生成条码图像时设置 HTTP header 失败

PHP failed to set HTTP header when generating bar code image

我正在使用 composer 包 Piceq\Barcode 生成条形码图像。我只是通过简单的测试代码开始使用它:

$barCode = new Picqer\Barcode\BarcodeGeneratorPNG();
$barCode = $barCode->getBarcode($inputs['code'], $barCode::TYPE_CODE_128);

ob_clean();
header('Content-Type: image/png');
echo $barCode;

$barCode 的内容看起来有点像生成图像的二进制内容。问题是它作为 text/html 发送到浏览器。我错过了什么导致 HTTP header 设置不正确?

我不确定是什么原因,但问题原来是 echo 引起的。将 echo 更改为 die() 即可解决问题。

这是工作代码。

$barCode = new Picqer\Barcode\BarcodeGeneratorPNG();
$barCode = $barCode->getBarcode($inputs['code'], $barCode::TYPE_CODE_128);

header('Content-Type: image/png');
die($barCode);