代码之家  ›  专栏  ›  技术社区  ›  NoobishPro

PHP服务的映像始终损坏

  •  0
  • NoobishPro  · 技术社区  · 6 年前

    每当我尝试用php服务一个图像时,它都会声明该图像已损坏/损坏,并在Google Chrome中给出以下警告:

    资源解释为文档,但以mime类型传输 图片/png

    但是,情况如下:

    1. 这个脚本在多个服务器上运行良好,而不是在这个服务器上。
    2. 我使用了多个图像和扩展名
    3. 如果我把它们放在 img SRC作为base64解码图像
    4. 出于测试目的,我把它放在index.php的第一行,但没有用。
    5. 我的文件不是UTF-8 BOM
    6. 我个人看不到任何惊喜的标题

    我尝试过的例子:

    $imgpath = 'assets/img/dropdown-arrow.png';
    $type      = pathinfo($imgpath, PATHINFO_EXTENSION);
    $data      = file_get_contents($imgpath);
    $base64    = 'data:image/' . $type . ';base64,' . base64_encode($data);
    header('Content-Type: image/png;'); // also tried with charset=UTF-8 and such
    echo base64_decode($base64);
    exit();
    

    示例2(在其他服务器上工作示例):

    // Set the content type header - in this case image/png
    header('Content-Type: image/png; charset=UTF-8');
    // integer representation of the color black (rgb: 0,0,0)
    $background = imagecolorallocate($img, 0, 0, 0);
    
    // removing the black from the placeholder
    imagecolortransparent($img, $background);
    
    // turning off alpha blending (to ensure alpha channel information
    // is preserved, rather than removed (blending with the rest of the
    // image in the form of black))
    imagealphablending($img, false);
    
    // turning on alpha channel information saving (to ensure the full range
    // of transparency is preserved)
    imagesavealpha($img, true);
    
    // Output the image
    imagepng($img);
    

    ---所以,再一次,我已经把我的框架作为中间人,试图直接从index.php的第一行运行它。

    所以,出于某种奇怪的原因,当我设置 content-type image/png 一切都在走下坡路。

    有人知道这是为什么吗?这是我的代码遗漏的东西吗?这是我无法用我的代码(服务器端)修复的问题吗?我只是错过了一些非常明显的事情吗?


    基本服务器信息:

    我用php-fpm在Apache2.4.5上运行。(尽管切换到php-fastcgi没有改变)在php 7.2.3上


    响应头:

    连接: 保持活力

    内容类型: 图片/png

    戴特: 2018年7月13日星期五19:51:37格林尼治标准时间

    保持活力: 超时=5,最大=99

    服务器: Apache/2.4.25(Debian)

    传输编码: 块状的


    更新/修复

    显然,有人(不是我,真的!)在 <?php 标记在一个小文件中,该文件包含在整个MVC中。移除那个空间解决了所有问题。花了好几个小时才找到,所以,对于任何阅读的人来说,这是一个教训:确保代码的格式保持整洁,并始终将 <?PHP 一开始就有标签。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Felippe Duarte    6 年前

    您可以直接输出,无需进行base64_编码/解码

    $imgpath = 'assets/img/dropdown-arrow.png';
    $data    = file_get_contents($imgpath);
    header('Content-Type: image/png;');
    echo $data;
    exit();
    
        2
  •  0
  •   user10077952    6 年前

    在示例2中,您的头表示您的数据是utf8编码的。 为什么? 您的数据是二进制文件 不编码UTF8