0

I am using GD library and I tried to add a html on image using php echo.

<?php
$image = imagecreatefrompng("grafika.png");
$black = imageColorAllocate($image, 255, 255, 255);
$font = 'arial.ttf';
$text = 4;
if($text == 4) {
      echo '<div style="background-color: yellow; width: 100px; height: 100px;">some text here</div>';
    }
imagettftext($image, 16, 0, 50, 100, $black, $font, $text);
header("Content-type:  image/png");
imagepng($image); 
?>

What am I doing wrong ? Is there a different way to do this ?

Nils Munch
  • 8,805
  • 11
  • 51
  • 103

2 Answers2

1

You've got two problems. You're dumping html into your output stream, and then following up that html with the raw binary contents of a .png image.

Presumably you've got

<img src="yourscript.php">

which means that you're sending HTML into a context where only binary image is allowed. And somehow expecting the browser to know that you're sending HTML AND an image and somehow be able to separate them.

Since you're doing that echo, the html becomes PART of the image, and the resulting image will be treated as corrupt by pretty much every browser in the universe. They're expecting a PNG, which has a very specific header format. HTML won't match that format, so obviously the image is corrupt.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

If you are allowed to embed the some text here into the image than you can use the imagefilledrectangle function:

<?php
$image = imagecreatefrompng("grafika.png");
$black = imageColorAllocate($image, 255, 255, 255);
$font = 'arial.ttf';
$text = 4;
if($text == 4) {
      imagefilledrectangle($image, 16, 0, 0, 50, 100, rgbcolorallocate($image, 255, 255, 0));
      imagettftext($image, 16, 0, 0, 0, $black, $font, 'some text here');
    }
imagettftext($image, 16, 0, 50, 100, $black, $font, $text);
header("Content-type:  image/png");
imagepng($image); 
?>

Also you can use the imagettfbbox function to calculate the bounding box of the texts.

Radu Dumbrăveanu
  • 1,266
  • 1
  • 22
  • 32