Issue
I'm trying to only horizontally align text on an image in php gd library like you'd do with "text-align: center" so the text isn't going out of the image if it's too large.
<?php
// (A) OPEN IMAGE
$img = imagecreatefrompng('LOGO.PNG');
// (B) WRITE TEXT
$txt = "Divine Magnificent Endurance";
$font = "C:/xampp/htdocs/testImages/ArialCE.ttf";
$white = imagecolorallocate($img, 0, 0, 0);
$width = imagesx($img);
$height = imagesy($img);
$text_size = imagettfbbox(24, 0, $font, $txt);
$text_width = max([$text_size[2], $text_size[4]]) - min([$text_size[0], $text_size[6]]);
$text_height = max([$text_size[5], $text_size[7]]) - min([$text_size[1], $text_size[3]]);
$centerX = CEIL(($width - $text_width) / 2);
$centerX = $centerX<0 ? 0 : $centerX;
$centerY = CEIL(($height - $text_height) / 1.3);
$centerY = $centerY<0 ? 0 : $centerY;
imagettftext($img, 18, 0, $centerX, $centerY, $white, $font, $txt);
imagesavealpha($img, true);
// (C) OUTPUT IMAGE
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
Solution
I had to implement a similar functionality when generating avatars, I solved that by grabbing the third and sixth value of imagettfbbox
, that is the lower right corner in the X position and the upper right in the Y position, having those I subtract that from the image height and width, then divide that value in half, round up and grab the absolute value, and those will be my x
and y
coordinates.
I played around with which values and math operations would produce the best results and this gave me the desired centering.
$centerY = abs(ceil(($height - $text_size[5]) / 2));
$centerX = abs(ceil(($width - $text_size[2]) / 2));
I wrote a post about it on my Dev account that could be of use. I hope that gives you some help in the right direction.
Answered By - Kim Hallberg Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.