如何使PHP脚本用作img源?

时间:2018-08-05 14:46:51

标签: php html image-processing

我想跟踪电子邮件上的一些使用情况统计信息,并想到将我使用的图像放在跟踪脚本中,然后将其添加到电子邮件中。

但是,我无法正常工作。我的代码如下:

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8"/>
    <title></title>
</head>
<body>
<img src="test.php">
</body>
</html>

PHP代码test.php:

  <?php
 // The image to return
$image=imagecreatefrompng("images/dl-front.png");

// ** Output image to browser
header('Content-type: image/png');
imagejpeg($image);

// ** Destroys the image
imagedestroy($image);
?>

我得到了损坏的图像链接,如下所示:

output in browser

2 个答案:

答案 0 :(得分:0)

编辑:在OP编辑https://stackoverflow.com/revisions/51695324/1

之前给出了此答案。

我不确定,但是您正在创建一个 .png 图片,然后将使用header('Content-type: image/jpeg');将其显示为 .jpg

所以我想如果您想显示 .png 图片,则必须使用
header('Content-type: image/png');

答案 1 :(得分:0)

您可以使用以下PHP脚本解决问题:

$image = 'images/dl-front.png';
if(!file_exists($image)){
    die("File does not exist");
}
header('Content-Type:image/png');
header('Content-Length: ' . filesize($image));
header('Content-disposition: filename="dl-front.png"');
readfile($image);