Jessica Tsui
Jessica Tsui

Reputation: 55

Creating a dynamic image with php and drupal

I am new to drupal and php. Right now I am trying to customise my own drupal page by editing the page.tpl.php template in a zen sub-theme, and so far all the php code related with data and text are working fine on the page.

However when I am trying to further customise the page by trying to add a dynamic image through php, things are not working. The site now returns a broken link icon which blocks everything else that should be displayed on the page. I have tested the code which generates the dynamic image on an individual php page and it is working well. I wonder how can I resolve this issue and let the dynamic image be properly displayed on my drupal site? Many thanks in advance.

Here is my code

<div id="projects">
<?php
global $node;
$projectname = db_query("SELECT title  FROM {node} 
where type='project' and uid= :uid", array(':uid' =>$user->uid))-    >fetchAll();
if ($projectname){
foreach($projectname as $item) {
print $item->title ;
echo "<br>";  
}
}
else{
print "no project";
}  
?>

#this is the chunk of codes that generates the dynamic image
<?php
//$image = @imagecreate(200, 20)or die("Cannot Initialize new GD image   stream");
$image = imagecreate(200, 20);
$background = imagecolorallocate($image,0,0,0);
$foreground = imagecolorallocate($image,255,255,255);
imagestring($image,5,5,1,"This is a Test",$foreground);
header("Content-type: image/jpeg");
imagejpeg($image);
imagedestroy($image);
?>

</div>

Upvotes: 0

Views: 321

Answers (1)

Cyrbil
Cyrbil

Reputation: 6478

The image you generate need to be in its own page. imagejpeg will print the raw image binary output.

For your web html page to display it, you can import it with a basic <img src="">.

Resume:

  • image.php => render in full binary an image
  • page.php => standard web html page with <img src="image.php"> somewhere to fetch your dynamically generated image

Edit: I may have read the question to fast, it still not clear for me...
Most common issue are that errors or text outputs have been send with the image and corrupt the raw output. Removing the header to display temporary the output will help showing what have been send. Also care with <?php blocks, a single space before your php code will corrupt the image.
In short: image.php must only return raw binary image data.

Upvotes: 1

Related Questions