Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an inline image generated on the fly using PHP GD

Tags:

php

gd

I am trying the generate an image on the fly by merging images using PHP GD. I want to know if there is a way I can display the image inside my webpage without the need of storing it somewhere on server.

Like for example I created the following code for merging the images...

function create_image() {
   $main_image = imagecreatefrompng("images/main.png");
   $other_image = imagecreatefrompng("images/other.png");
   imagecopy($main_image, $other_image, 114, 53, 0, 0, 49, 34);
   imagepng($main_image);
   imagedestroy($other_image);
}

Now my html code till now was...

<div class="sidebar-avatar">
   <img src="avatar_pattern.png" class="pattern1" width="430" height="100" />
</div>

How should I call the php function so that it displays the image generated in the div I have designated for it.

Update: I found the use of Content-type: image/png but that would mean I will have to display the image on a separate page not inline.

like image 414
vikmalhotra Avatar asked Jan 25 '11 05:01

vikmalhotra


3 Answers

Convert it to Base64 with base64_encode and echo it as a dataURI in an img tag !

Inline Images with Data URLs

like image 127
Aweb Avatar answered Sep 24 '22 16:09

Aweb


You can either:

  1. Display the image as data: http://en.wikipedia.org/wiki/Data_URI_scheme (Warning: High bandwidth consumption.)
  2. Make a separate file that display the image, such as display_image.php

And use the code:

<img src="display_image.php">

With the header and code you have shown.

like image 23
Nican Avatar answered Sep 21 '22 16:09

Nican


<img src="image.php?other_image=(filename)">

and create your image in image.php, output with

header('Content-Type:image/png');imagepng($main_image);

You can also put the image creation part in the same script:

if($other_image=$_GET['other_image'])
{
    // create image
    ...
    // output image
    header('Content-Type:image/png');
    imagepng($main_image);
}
else
{
    // default behaviour
    ...
    echo '<img src="',basename(__FILE__),'?other_image=',urlencode('images/other.png'),'">';
    ...
}

Take care to prevent injections!

like image 44
Titus Avatar answered Sep 25 '22 16:09

Titus