Jump to content

How to get image with custom font to show up on browser?


brenda

Recommended Posts

I need to be able to create an image from user input.  I have found a couple of samples that purport to do that but when I copy the code I can't get it to work.  I would appreciate advice as to what I am doing wrong please.

 

One example I tried is from a tutorial on this site: http://www.phpfreaks.com/tutorial/php-add-text-to-image

 

Now perhaps there is something I am doing wrong when I call on the image that is supposed to display but given that I have tried the same code with other images and it works I can't see what I am doing wrong, unless there is something in the nature of scripts that requires some extra steps.  Here is my code to see the image (note that 'myscript.php' in my code is in the same folder as the code I am calling:

 

<html>

<head>

<title>Using Images Created by Scripts</title>

</head>

<body>

 

<h1>Generated Image Below ...</h1>

 

<img src="myscript.php"/>

 

</body>

</html>

 

Can anyone help?

 

Thank you

Link to comment
Share on other sites

// Path to our font file
$font = 'arial.ttf';
$fontsize = 10;

// array of random quotes
$quotes = array(
"http://www.flingbits.com is the greatest invention since sliced bread! Except you can't slice it...",
"Did you hear about the guy whose whole left side was cut off? He's all right now.",
"There was a sign on the lawn at a drug re-hab center that said 'Keep off the Grass'.",
"Police were called to a daycare where a three-year-old was resisting a rest.",
"A hole has been found in the nudist camp wall. The police are looking into it.",
"When a clock is hungry it goes back four seconds.",
"Time flies like an arrow. Fruit flies like a banana.",
"Local Area Network in Australia: the LAN down under.",
"Alcohol and calculus don't mix so don't drink and derive.");

// generate a random number with range of # of array elements
$pos = rand(0,count($quotes)-1);
// get the quote and word wrap it
$quote = wordwrap($quotes[$pos],20);

// create a bounding box for the text
$dims = imagettfbbox($fontsize, 0, $font, $quote);

// make some easy to handle dimension vars from the results of imagettfbbox
// since positions aren't measures in 1 to whatever, we need to
// do some math to find out the actual width and height
$width = $dims[4] - $dims[6]; // upper-right x minus upper-left x 
$height = $dims[3] - $dims[5]; // lower-right y minus upper-right y

// Create image
$image = imagecreatetruecolor($width,$height);

// pick color for the background
$bgcolor = imagecolorallocate($image, 100, 100, 100);
// pick color for the text
$fontcolor = imagecolorallocate($image, 255, 255, 255);

// fill in the background with the background color
imagefilledrectangle($image, 0, 0, $width, $height, $bgcolor);

// x,y coords for imagettftext defines the baseline of the text: the lower-left corner
// so the x coord can stay as 0 but you have to add the font size to the y to simulate
// top left boundary so we can write the text within the boundary of the image
$x = 0; 
$y = $fontsize;
imagettftext($image, $fontsize, 0, $x, $y, $fontcolor, $font, $quote);

// tell the browser that the content is an image
header('Content-type: image/png');
// output image to the browser
imagepng($image);

// delete the image resource 
imagedestroy($image);
?>

 

If you have the GD extension enabled and arial.ttf in the same folder, I think it should work.

Comment out the header() line and browse to myscript.php directly. Do you see any error messages?

Link to comment
Share on other sites

I get the following:

 

Warning: imagettfbbox() [function.imagettfbbox]: Invalid font filename in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 24

 

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 33

 

Warning: imagecolorallocate() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 36

 

Warning: imagecolorallocate() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 38

 

Warning: imagefilledrectangle() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 41

 

Warning: imagettftext() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 48

 

Warning: imagepng() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 53

 

Warning: imagedestroy() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\PHPbook\Examples\14\myscript.php on line 56

Link to comment
Share on other sites

Looking at those error messages:

 

line 24: is this something to do with what you said about needing arial.ttf in the same folder?  I don't understand what that means.

 

line 33: don't understand that either.

 

the remaining lines- i don't know what it is saying needs to be within the ().

 

Your further advice is much appreciated.

 

Brenda

Link to comment
Share on other sites

"arial.ttf" is the file name of a font.

 

In order to put a font in an image, you need to have the font file. A font file is like any other file. It doesn't have to be "arial.ttf". You can download lots of fonts on the internet.

 

When this particular script is run, it is looking for a file named "arial.ttf", but you don't have that file, so it's throwing up all over itself. The script is scared, and doesn't know what to do, but you can help it. You can be the hero and give the script the font it needs. All you have to do is download a font and put it in the same directory as the script, so they can live together in harmony.

 

BE CAREFUL, though! You might download a font that is not named "arial.ttf". In that case, you will need to EDIT the script. That means you have to open it up in your text editor and change "arial.ttf" to something else. However, I don't know what that is. You have to figure that one out on your own, but it shouldn't be too hard, because it will be whatever the name of the font is that you downloaded.

 

For instance, if you download a font called "myAwesomeFont.ttf", you will have to edit the script and change "arial.ttf" to "myAwesomeFont.ttf".

 

Please let me know if you have any questions. I know it can be tricky.

Link to comment
Share on other sites

Thanks very much Socratesone.  You are a legend!

 

Can I ask you a follow on question please (it is a follow on in my mind at least).

 

If the script that I want to be shown as an image is input by the user, as in the following script, should the whole process work the same as it now does, thanks to your help (and that of Requinix) with the script that I sent you earlier?

 

I can get the form to work and create an image containing the input text in the browser, but if I then put the name of that file into my html script (as provided in my initial post) as <img src="imagestring.php"/>all  I get is the placedholder for an image.

 

I would be so grateful if you could resolve this for me as this would be the end of my long search for an answer.

 

<?php

if (!$_POST) {

//show form

echo "

<html>

<head>

<title>Image Creation Form</title>

</head>

<body>

<h1>Create an Image</h1>

<form method=\"POST\" action=\"".$_SERVER["PHP_SELF"]."\">

<p><strong>Image Size:</strong><br/>

W: <input type=\"text\" name=\"w\" size=5 maxlength=5> H: <input type=\"text\" name=\"h\" size=5 maxlength=5>

<p><strong>Background Color:</strong><br/>

R: <input type=\"text\" name=\"b_r\" size=3 maxlength=3> G: <input type=\"text\" name=\"b_g\" size=3 maxlength=3>

B: <input type=\"text\" name=\"b_b\" size=3 maxlength=3>

<p><strong>Text Color:</strong><br/>

R: <input type=\"text\" name=\"t_r\" size=3 maxlength=3> G: <input type=\"text\" name=\"t_g\" size=3 maxlength=3>

B: <input type=\"text\" name=\"t_b\" size=3 maxlength=3>

<p><strong>Text String:</strong><br/>

<input type=\"text\" name=\"string\" size=35>

<p><strong>Font Size:</strong><br/>

<select name=\"font_size\">

<option value=1>1</option>

<option value=2>2</option>

<option value=3>3</option>

<option value=4>4</option>

<option value=5>5</option>

</select>

<p><strong>Text Starting Position:</strong><br/>

X: <input type=\"text\" name=\"x\" size=3 maxlength=3> Y: <input type=\"text\" name=\"y\" size=3 maxlength=3>

<p><input type=\"submit\" name=\"submit\" value=\"create image\">

</form>

</body>

</html>";

} else {

//create image

//create the canvas

$myImage = ImageCreate($_POST["w"], $_POST["h"]);

 

//set up some colors

$background = ImageColorAllocate ($myImage, $_POST["b_r"], $_POST["b_g"], $_POST["b_b"]);

$text = ImageColorAllocate ($myImage, $_POST["t_r"], $_POST["t_g"], $_POST["t_b"]);

 

// write the string at the top left

ImageString($myImage, $_POST["font_size"], $_POST["x"], $_POST["y"], $_POST["string"], $text);

 

//output the image to the browser

header ("Content-type: image/png");

ImagePNG($myImage);

 

//clean up after yourself

ImageDestroy($myImage);

}

?>

 

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.