Search code examples
phpimagepng

Displaying PNG file from PHP


I'm using a PHP library to display a small png image. It works fine placed into its own PHP file, right here: https://www.sidesay.co/test_draw.php

The code is quite simple.

<?php

    require './libraries/Sparkline-master/autoload.php';
    
    $sparkline = new Davaxi\Sparkline();
    $sparkline->setData(array(2,4,5,6,10,7,8,5,7,7,11,8,6,9,11,9,13,14,12,16));
    $sparkline->display();
    
?>

But when I include the above code into my larger php file for displaying with the rest of the webpage, I get junk data where the image should be, that looks like this:

�PNG IHDRPغ� pHYs���+�IDATX��OLZw�?���4H�@\’j�DOzX�d��SM��,f.��%���Poۚ�^l�fa�lz/�^�ɥä�9�AuB��C�{(�oP�):u�����}�߇���C�(��e18��q��Rĥ̡� �D�n1A�9��R�2�C)��I��ID9�A_���L_�A�//

etc.

Any ideas?


EDIT: I've created a quick PHP file to show the problem. Including a Header does not resolve the problem. It only works without HTML or if I place the PHP at the top it works but my HTML will not display at all.

<html>
<head>
    <title>TEST</title>
</head>

<?php

    header('Content-type: image/png');
    require './libraries/Sparkline-master/autoload.php';
    
    $sparkline = new Davaxi\Sparkline();
    $sparkline->setData(array(2,4,5,6,10,7,8,5,7,7,11,8,6,9,11,9,13,14,12,16));
    $sparkline->display();

?>


<body>
    <br>
    <p>Not displaying</p>
</body>
</html>

The output to this can be seen here:

https://www.sidesay.co/error_draw.php

I have also tried using the imagepng function but the junk data persists.

imagepng($sparkline->display());

Solution

  • You cannot display any html in this file.

    But, to display the PNG, you have to add this:

    <?php
        header('Content-Type: image/png');
    ?>
    

    Adding this will make the browser display only an image: enter image description here