3

I feel quite stupid but I can't understand how to display the output of the imagepng() function.

What I currently do is (and it works fine) :

<img src=<?php echo getImage($element); ?> />

function getImage($element){
    return $bdd[$element]; // the result is a string with the path to the image
}

But I would love to draw some circles on the image, so here is what I would like to do (and it does not work) :

<img src=<?php echo getImage($element); ?> />

function getImage($element){
    $image = imagecreatefrompng($bdd[$element]);
    $ellipseColor = imagecolorallocate($image, 0, 0, 255);
    imagefilledellipse($image, 100, 100, 10, 10, $ellipseColor);
    imagepng($image);

    return $image // why does that image resource not display ?
}

But it does not display anything else than symbols.. I assume it returns a full image and not a path to the image.. so How should I display my image with the circle on it ?

ps : I also tried to create a page getImage.php that would be called by <img src=<?php echo 'getImage.php?element=' . $element; ?> /> but with no success

Arcyno
  • 4,153
  • 3
  • 34
  • 52

2 Answers2

3

You have to do something like this

<img src="image.php">

And in the image.php you use your code

$image = imagecreatefrompng($bdd[$element]);
$ellipseColor = imagecolorallocate($image, 0, 0, 255);
imagefilledellipse($image, 100, 100, 10, 10, $ellipseColor);
imagepng($image);
Dave Plug
  • 1,068
  • 1
  • 11
  • 22
  • I didn't know a PHP file could be used as "src=" (+1), first time I see this. For those who can't make "image.php" to work, I made it work by adding `ob_start();` at the beginning and `ob_end_flush();` and `ob_end_clean();` at the end (just **before** `imagepng($image);`). – Jose Manuel Abarca Rodríguez Dec 21 '16 at 17:41
  • @JoseManuelAbarcaRodríguez could please give reference not docs how did you guessed or found about these ob_XXX() calls, because it's been a whole day of grief, trying different thumbnail creator codes that did not want to display this image resource. thanks – Meryan Mar 30 '20 at 03:33
  • @Meryem, try this answer ► https://stackoverflow.com/a/3695085/3298930 – Jose Manuel Abarca Rodríguez Mar 30 '20 at 15:32
1

I finally got my answer on how to display the image inside an HTML page : I need to put the code in another file displayImage.php and make a call to this page from the <img>tag :

Main file with html tag:

<img src="displayImage.php?element='<?php echo $element; ?> />

displayImage.php :

<?php

header('Content-Type: image/png');
$image = imagecreatefrompng($bdd[$element]);
$ellipseColor = imagecolorallocate($image, 0, 0, 255);
imagefilledellipse($image, 100, 100, 10, 10, $ellipseColor);
imagepng($image);
imagedestroy( $image );

?>
Arcyno
  • 4,153
  • 3
  • 34
  • 52