-1

I have found following way of creating a sample image via php in a separate php file which then is included in the img src attribute:

<img src="image_creator.php">

In the file "image_creator.php" I do following:

header ("Content-type: image/png");
$display_img=imagecreate(100, 50);
imagecolorallocate($display_img, 255, 255, 125);
imagepng($display_img);
imagedestroy($display_img);

This is a simplified version which works. I do something more about it which is not important for my question.

My question: how is it possible to include above php code from the separate file "image_creater.php" directly in the leading php file including the HTML img statement?

I tried to use the php code inside a php function and put that function inside the img src attribute but it did not work. The background of my question is that I additionally use a text code to be printed inside the image and I don't want to disclose this text code via "image_creator.php?code=xxx" which would be visible in the HTML code of the img of course.

  • You can't as such since that PHP file outputs an image (it *is* `image/png`) - you don't embed image code directly into HTML ... the disclaimer being embedding base64 encoded images, you *could* change the PHP file to instead echo out the [base 64 encoded image](https://stackoverflow.com/questions/1207190/embedding-base64-images) I suppose. – CD001 Jul 13 '18 at 15:31
  • 1
    _"and put that function inside the img src attribute but it did not work"_ - of course it didn't - when you embed a "static" image you don't go and copy&paste the actual binary content of the image file into the `src` attribute either, right? And this is practically the same thing. Data URI would be the keyword if you really want this - but it blows up the data volume and makes caching of images used in multiple places impossible, so you probably rather don't want that actually. – CBroe Jul 13 '18 at 15:31

1 Answers1

0

If I'm understandingly correctly, you can include the image via base64 encoding:

<img src="<?php echo require('image_creator.php'); ?>">

And inside of image_creator.php you would do:

<?php
$display_img=imagecreate(100, 50);
imagecolorallocate($display_img, 255, 255, 125);
ob_start();
imagepng($display_img);
imagedestroy($display_img);
$img = ob_get_clean();
return 'data:image/png;base64,' . base64_encode($img);
?>
Kyle
  • 3,935
  • 2
  • 30
  • 44
  • Thanks for your input! Along with the other feedback so far I think I'll go for another solution than I thought of. a) simply saving the image file and accessing it afterwards or b) working with encryption / decryption – Daniel B. Jul 13 '18 at 16:12