0

Possible Duplicate:
Headers already sent by PHP

echo "how";

$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);

I want to display out the string "how" and the image at the same time, but I don't want to save this image in file.

The code above doesn't work. If I take away the line echo "how", it works fine. So how can I modify it if I want to display the string and image at the same time?

Community
  • 1
  • 1
user1645112
  • 65
  • 2
  • 4
  • Look at this page: http://en.wikipedia.org/wiki/Data_URI_scheme. In the end, you're going to want to remove the `header('Content-type ...');` and encode using base64.... here's actually a question on SO that gives an example in the question: http://stackoverflow.com/questions/1461793/ie6-gd-and-php-image-outputting – jeremy Sep 04 '12 at 23:55

1 Answers1

1

As Nile already pointed out, you want to use a Data-URI for the image.

A working code example using your code is as follows:

echo "how";

$im         = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
$tmpImg     = tempnam('/tmp', 'image');

imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);
imagejpeg($im, $tmpImg);
imagedestroy($im);

echo '<img src="data:image/jpeg;base64,' . base64_encode(file_get_contents($tmpImg)) . '">';

unlink($tmpImg);

What happens? It's more or less the code you used, but the image is written to a temporary file instead of directly being sent to the browser - thats the second parameter to imagejpeg. Then the content of the temporary file is put into a Data-URI using Base64-Encoding and that DataUri is then set as src of an image-tag.

You will want to delete the temporary file at the end!

If you want to omit the temporary file, you can use output buffering to capture the image. This would look something like the following:

echo 'how';

$im         = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

ob_start();
imagejpeg($im);
imagedestroy($im);
$image = ob_get_contents();
ob_end_clean();

echo '<img src="data:image/jpeg;base64,' . base64_encode($image) . '">';
heiglandreas
  • 3,803
  • 1
  • 17
  • 23