1

I am trying to print some text to a png file. I have tried everything, but no luck.

Here is my code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type" content="image/jpeg" />
</head>

<body>

<?php
// Create the image
$im = imagecreatetruecolor(100, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'fonts/FRE3OF9X.TTF'; //HAVE CHECKED THIS AND FILE EXISTS

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagejpeg($im);

imagedestroy($im);
?>

</body>
</html>

I have tried various font files and checked that the file is being found by changing the filename to see if I get an error. Is there any additional stuff I need to install on the server to make this work?

The output is garbled text (e.g. tuvwxyz������).

2 Answers2

1

Why are you sending two Content type headers? Remove the first one which says its text/html

Remove: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Only this Content-Type should stay for your image

<meta http-equiv="Content-Type" content="image/jpeg" />
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
  • Thanks for the response. I left that in because I need it for the rest of the page (not included in the code). However, just for testing purposes, I removed it from my code and I just get different garbage. – Saville Kaufman Oct 31 '13 at 08:15
  • You cannot print an image and html from same page. You have to send one specific content type back in response of an HTTP request. `I just get different garbage`: That is actually the image being generated, load that url in an image tag and you'll see, or also try opening it in a new browser session. – Hanky Panky Oct 31 '13 at 08:17
  • The code I supplied is current all I have on the page (taken out the text/html content type). When you say load the URL into an image tag, do you mean on on my page have where barcode.php is the code supplied above? – Saville Kaufman Oct 31 '13 at 09:43
  • SORRY, been a bit stupid. Thanks to your advise have solved problem. Removed HTML, HEAD and BODY, reintroduced "header('Content-Type: image/png');" and placed file in IMG tag as suggested. Thanks so much for your help. – Saville Kaufman Oct 31 '13 at 10:41
0

You can always use base64 encoded strings and show them as an image: Embedding Base64 Images

Community
  • 1
  • 1
Edd Turtle
  • 1,511
  • 1
  • 13
  • 24