简体   繁体   中英

Writing text on the image with PHP and GD

My website has a picture generator. It allows visitors to write a custom text on an image.

I handle the situation by displaying the picture and using Javascript, so they can write on the picture (to preview how the picture will look like). After they press submit I get x&y coordinates, text and font size.

(I also support multiply font sizes)

For writing the text on the image I use the ImageTTFText function.

Ok, so far everything was good. Now the problem I have is how to know when the sentence is too long to fit in one line. I came across the wordwrap function, but it's not reliable. It splits the sentence depending on the number of chars. But, for example, if you type 'I' ten times and 'D' ten times you will see there is a difference in width.

Ok, then I came across ImageTTFBBox which will calculate the size of the box so I will know when it's too long. Well this is fine but how could I split the sentence then? (by words).

I would be very grateful if anyone could give me an answer.

my logic would be to add as many words to each line as possible without having to cut a word. So, I would add a word to a line, check its rendered size with ImageTTFBBox() , and repeat until the line overflows(and then obvious remove the word that caused the overflow). If you come across the situation where the line overflows and there's only one word on the line, then you must cut the word. you will be calling ImageTTFBBox() many many times.

If you are using HTML5, you could ask Javascript to give you some help, before sending over. Assuming you have a canvas (even created in code) and a context ctxt you could do:

ctxt.font = "14pt Arial";
ctxt.textAlign = "left";
ctxt.fillStyle = "#000";
ctxt.fillText(text, x, y);
var metrics = ctxt.measureText(text);
var width = metrics.width;

Now you know how wide your text is, and can do some basic word wrapping. Say your effective width (image width minus inside margin) is 180 px, and your text width is 679 px. That's a +/- 25% ratio (26.05%). Use that ratio to extract the first 25% of the sentence, see if it fits in the width, draw, and move down a line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM