dynamic-image-generation

imagettftext(): calculate font size to ensure text fits image width

青春壹個敷衍的年華 提交于 2019-11-28 11:34:39
I'm using imagettftext() to write dynamic text on an image and I want it to fit my image width. How can I calculate the font size by the text lenght? You can calculate the bounding box of TTF text before outputting it with the imagettfbbox function. Unfortunately there is no direct way of scaling to fit a width, so you'll have to do it yourself. One way of doing it is to pass the text with a default font size of, say 20, to imagettfbbox and retrieve the width from it. You can then calculate how much smaller or bigger the text should be to fit the size you want by calculating a scale factor: