php how to fit a text into a box - php

I have the bounds of a rectangular box.
Is it possible to fit a text (with custom font) into the box while not knowing the text size.
I mean, is there a php function which sets the proper text size so that the text is fitted into the user-defined box?
I do not need text wrapping.
The only functions I found are imagettfbbox and imagettftext.
imagettfbbox does exactly the opposite(gives the bounds, provided a font size) while imagettftext is used to write text on an image, only if fontSize is known.

Are you using php gd? If so, then I would use imagettfbbox. Just define all the parameters except size. Then outside of that loop on size until it is small enough to fit in your defined space. I've done this before. It doesn't do any actual image creative in memory, so it's very fast (much faster than actually creating the image).
for($size=40;$size>5;$size--){
$sizearray=imagettfbbox ( $size , 0- , 'font.ttf' , $message );
$width=$sizearray[0] + $sizearray[4];
if($width<$threshold/*you define*/){
//you've got your $size
break;
}
}

Related

How to create png from array of pixel color data in PHP?

Lets say I have an arrays of pixels. Basically an array of this data {x,y,r,g,b,a} for each pixel.
How would I go about converting all this data into an actual image file (png preferably)?
Could not find a solution. Any help would be very appreciated.
I had some time to code up a little example. You should be able to see and note that:
the red component increases towards the bottom of the image
the green component increases towards the right of the image
the blue component is absent
the alpha channel is random and between 0 (opaque) and 127 (fully transparent)
// Define width and height
$w=800;
$h=600;
// Create truecolour image so we can have infinitely many colours rather than a limited palette
$img=imagecreatetruecolor($w,$h);
imagesavealpha($img,true);
imagealphablending($img,false);
// Iterate over all pixels
for($y=0;$y<$h;$y++){
for($x=0;$x<$w;$x++){
$r = round(255*$y/$h);
$g = round(255*$x/$w);
$b = 0;
$alpha = rand(0,127);
$color = imagecolorallocatealpha($img,$r,$g,$b,$alpha);
imagesetpixel($img,$x,$y,$color);
}
}
// Save result
imagepng($img,"result.png");
I'll admit I haven't actually used this API, but looks like PHP has what you're looking for.
You create an image identifier with imagecreate or one of the related functions, then color in each pixel with imagesetpixel, using a color identifier created with imagecolorallocatealpha. From there you should be able to output as a PNG with imagepng.
It's worth noting that this image library seems to support drawing lines and shapes and other structures higher than the per-pixel level, so I'd also look into whether your code necessarily needs to build a big pixel array, rather than drawing the image some other way.

Creating a dynamically sized text overlay with iMagick

I am trying to create a text overlay on an image using php and iMagick. The crucial part is that I want the text size to scale to fill a predefined box, so I do not want to set a fixed font size. I have found the code at ImageMagick - Text into rectangle but need to adapt this code for the iMagick. I seem to be able to do everything except the crucial part -size ${width}x100
Here's the code I have, with a few things that I have tried commented out
$draw = new ImagickDraw();
$draw->setGravity (Imagick::GRAVITY_SOUTHEAST);
$draw->setFont('Bookman-DemiItalic');
//$draw->setFontSize( 30 ); // don't want to set a fixed font size
$draw->setTextUnderColor('#00000075');
//$draw->setSize(0, 0, 200, 200); // error: Call to undefined method ImagickDraw::setSize()
//$draw->setViewBox(200, 200, 800, 800); // appears to do nothing
//$draw->rectangle(200,200,300,300); // this just draws a separate white box
$draw->annotation(100, 100, 'The quick brown fox jumps over the lazy dog'); // works, but it's a default (small) text size and the box simply fits the exact text with no border
$img->drawImage($draw);
Is there a size option that somehow I've missed in the docs?
Note that How can I wrap text using Imagick in PHP so that it is drawn as multiline text? partially addresses this issue, but it doesn't appear to offer scaling of the text to fit a fixed size box, rather a wrapping of text if the selected font size would cause the text to overrun. Though maybe I have misunderstood - I will give it a try!

text resize with php while using GD functions

I did found a topic similar to this, but I do not know if the solution is the same. So here is my question:
I'm using the GD functions to bild a web card generating program. The thing is that the card's backgound is generating by the $image = imagecreatefrompng(); function.
The card need's also a $cardname as "title" and a $desription as desription. For that I used the imagettftext(); function. But there is a problem, the card's size is 333x485, I need the text to be resized in order to fit in the background without resizing its height, but only the width!
To be more to the point, the $cardname should have width = 240 and height = 34, but if it doesn't fit, it goes off the background, I need a function that will resize its width in order to fit in 240px and leave the height to 34px always!
To understand it more look here: http://yugiohcardmaker.net. in the "name" you can add as much text you like, it will always fit in and in the right width and height!
I'm not going to try and code this as it will take too long, but here's the basic process:
Get the size of the bounding box for your text with imagettfbbox();
Create a new image with imagecreatetruecolor();
Write your text into your new image with imagettftext();
Use imagecopyresampled() to copy the new image with your text to your existing card, setting the parameters to shrink the width but not the height.
Note: the bounding box parameters returned by imagettfbbox()) can be fiddly to work with
You'll also need to be careful about alphablending and background colors to ensure that only your text pixels are copied.
Good luck!

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

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:
scale = targetWidth / bboxWidth;
Then draw the text with the proper size:
fontSize = 20 * scale;
using the imagettftext function. Fonts don't scale 100% perfectly this way, but you'll get a very good approximation.
See the documentation of imagettfbox here.
while (itsTooBigAccordingToimagettftext() && $fontSize > 0) {
$fontSize--;
}

Get the width and height of a string in pixel (PHP)

Is there any good function to calculate the pixel width and height? Can imagettfbbox be used to do that? I mean which ttf file is needed for the different fonts used by different browsers?
Thx
As PHP run's on the server there is no way to do that with PHP alone. The size of the text depends on the operating system, the browser (and the browser settings like zoom) of the client. You could however use javascript to get the size of an element once its rendered.
height = document.getElementById("elementId").style.height; // Will return 176px for example
width = document.getElementById("elementId").style.width; // Will return 176px for example
Hope this helps
There is a function (imagefontwidth and imagefontheight), but they only return the size of one character using the built-in fonts (which are all fixed-width). You'll get the width/height of the entire string by multiplying the number returned by the number of characters.
I don't know of any way that lets you get the width or height of a string using a custom font, but I'm interested in this too.
Hope this helps.

Categories