代码之家  ›  专栏  ›  技术社区  ›  Mark Lalor

PHP HTML图像输出

  •  10
  • Mark Lalor  · 技术社区  · 14 年前

    PHP manual 对于 base64_encode() 我看到了以下输出图像的脚本。

    <?php
    
    $imgfile = "test.gif";
    
    $handle = fopen($filename, "r");
    
    $imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));
    
    echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';
    
    ?>
    

    但是 怎样 你能输出一个动态创建的图像吗 GD ?

    我试过了:

    $im = imagecreatetruecolor(400, 400);
    
    imagefilledrectangle($im, 0, 0, 200, 200, 0xFF0000);
    imagefilledrectangle($im, 200, 0, 400, 200, 0x0000FF);
    imagefilledrectangle($im, 0, 200, 200, 400, 0xFFFF00);
    imagefilledrectangle($im, 200, 200, 400, 400, 0x00FF00);
    
    echo '<img src="data:image/png;base64,'.base64_encode(imagepng($im)).'" />';
    

    为什么不行?

    它似乎在工作 工业工程 但不是 火狐 . 我怎么做 跨浏览器?

    4 回复  |  直到 14 年前
        1
  •  15
  •   Tomasz Kowalczyk    14 年前

    好吧,对不起,我想得太快了:)

    imagepng() 将输出原始数据流 直接地 到浏览器,因此必须使用 ob_start() 以及其他输出缓冲手柄,以获得它。

    给你:

    ob_start();
    imagepng($yourGdImageHandle);
    $output = ob_get_contents();
    ob_end_clean();
    

    那是-你需要使用 $output 你的变量 base64_encode() 功能。

        2
  •  11
  •   Andrew    14 年前

    因为 imagepng 直接输出bool或图像流到输出。
    因此,为了获得图像数据,您应该使用如下的输出缓冲区:

    ob_start();
    imagepng($im);
    $image = ob_get_contents();
    ob_end_clean();
    echo '<img src="data:image/png;base64,'.base64_encode($image).'" />';
    
        3
  •  1
  •   Pekka    14 年前

    很可能是因为 data: 除非绝对没有办法解决,否则URI方案非常有限,而且很好使用。

    例如,在Internet Explorer中,直到IE8才起作用;在那里,有一个 global 32 kilobyte limitation 数据:URI。

        4
  •  0
  •   Sebastián Grignoli    14 年前

    您必须先将图像保存为PNG,然后从中读取图像以获取其内容值。

    http://www.php.net/manual/en/function.imagepng.php

    imagepng()不返回PNG文件。它直接输出到浏览器,然后返回一个布尔值,表示成功或失败。

    (来自PHP.NET:) 在将图像发送到浏览器时,PHP在内部使用一个临时文件,因此通过两次调用imagepng()将一无所获。