【问题标题】:PHP black screen instead of imagePHP黑屏而不是图像
【发布时间】:2019-04-12 11:49:37
【问题描述】:

我试图简单地显示带有以下代码的图像:

<?php
$plik = 'test.JPG';
header('Content-Type: image/jpeg');
$percent = 0.1;

list($width, $height) = getimagesize($plik);
$new_width = $width * $percent;
$new_height = $height * $percent;
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($plik);        
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

imagejpeg($image_p, NULL, 70);

imagedestroy($image_p); ?> 

不幸的是,我只能看到黑屏而不是图像,里面有小方块。

  1. 文件 test.JPG 存在,它与 obraz.php 文件位于同一目录中,文件 obraz.php 仅包含上面的代码。
  2. 我在 Chrome 上运行它。
  3. PHP 版本 5.2.11
  4. GD 版本捆绑(2.0.34 兼容)

有什么办法可以解决吗?

【问题讨论】:

  • imagecopyresampled 期望它的前 2 个参数是资源。你传递一个字符串作为它的第二个参数。
  • @Jeto 来自php.net/manual/en/function.imagecopyresampled.php 的示例#1 结构相同...
  • 不,不是。仔细看:)
  • @Jeto 好的,我看到了错误并修复了它,不幸的是,错误是一样的。我什至从我之前在评论中给出的链接中复制了代码,但效果仍然相同。
  • 你能把你的图片上传到某个地方并链接吗?代码看起来还不错。

标签: php html image


【解决方案1】:

试试这个,放置 ob_clean();在标题行之前。

您的 PHP 脚本在输出 PNG 图像内容之前发出 UTF-8 字节顺序标记 (EF BB BF)。此标记可能导致 PHP 将内容类型默认为 text/html。您随后设置标头的调用将被忽略,因为 PHP 已发送 BOM。

调用 PHP 的 ob_clean() 函数会在调用 header 函数之前清除输出缓冲区。

我从下面的链接中得到了答案。

https://stackoverflow.com/a/22565248/10349485

【讨论】:

  • 请通过编辑将所有解释添加到您的答案中
  • 谢谢你,杰森和尼科。我试图避免将别人的解决方案作为我的解决方案。我已经编辑了答案。
【解决方案2】:

我是否遗漏了什么,或者您可以简单地结束您的 php 标签并放置一个 HTML IMG 吗?

<?php
$plik = 'test.JPG'; 
$percent = 0.1; 
list($width, $height) = getimagesize($plik); 
$new_width = $width * $percent;
$new_height = $height * $percent; 
?> 

<img alt="test image" src="<?php echo $plik;?>" height="<?php echo $new_height;?>" width="<?php echo $new_width;?>"> 

除非我严重遗漏了某些东西,否则我不明白当您可以这样做时需要使用如此复杂的方法来创建图像。

【讨论】:

    【解决方案3】:

    所以我把文件放在其他服务器上并检查它。有一个关于标头的警告(可能无法再次声明)。 我检查并阅读了有关此警告的信息,并找到了解决问题的方法。 我只是用记事本++打开文件并将文本格式化为UTF-8 no BOM。 这使我的文件正常工作!

    感谢大家的帮助和努力!

    【讨论】:

      【解决方案4】:

      要诊断这样的问题,我建议making sure that PHP error reporting is on 并检查您是否从 PHP 中收到任何错误。

      在尝试使用 $image = imagecreatefromjpeg($plik); 分配内存时,您的可用内存似乎不足并出现致命错误。

      你可以增加允许的内存大小

      ini_set('memory_limit', '16M');
      ini_set('memory_limit', -1); // no limit
      

      但你可能想make sure your application is not leaking memory。

      PHP memory management documentation 也可能有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-13
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-05
        • 1970-01-01
        • 2020-09-22
        相关资源
        最近更新 更多