Write text over image dynamically and center the text - php

I have a script that is writing a text over an image.
It works fine, but the text is aligned to the left.
I am trying to center the text horizontally, but not sure how can I do that.
Here is the code that I have at the moment
//content type
header('Content-Type: image/png');
if (isset($_GET['text'])){$text = $_GET['text'];}else{$text = "";}
//font
$font = 'Ubuntu-Medium.ttf';
//font size
$font_size = 18;
//image width
$width = 400;
//text margin
$margin = 90;
//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
//Create a new text, add the word, and calculate the parameters of the text
$box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
//if the line fits to the specified width, then add the word with a space, if not then add word with new line
if($box[2] > $width - $margin*2){
$text_new .= "\n".$word;
} else {
$text_new .= " ".$word;
}
}
//trip spaces
$text_new = trim($text_new);
//new text box parameters
$box = imagettfbbox($font_size, 0, $font, $text_new);
//new text height
$height = $box[1] + $font_size + $margin * 2;
//create image
$im = imagecreatefromjpeg('source.jpg');
//create colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 51, 95, 32);
//color image
imagefilledrectangle($im, 0, 0, $width, $black);
// determine the size of the text so we can center it
$box = imagettfbbox($font_size, 0, $font, $text_new);
$text_width = abs($box[2]) - abs($box[0]);
$text_height = abs($box[5]) - abs($box[3]);
$image_width = imagesx($im);
$image_height = imagesy($im);
$x = ($image_width - $text_width) / 2;
$y = ($image_height + $text_height) / 2;
//add text to image
imagettftext($im, $font_size, 0, $x, $y, $black, $font, $text_new);
//return image
imagepng($im);
//frees any memory associated with image
imagedestroy($im);
Any ideas on how can I center the text?
I already centered the box that the text is placed, so the box is in the center of the image. The problem is that the text is aligned left and I need it in the center.

Related

PHP-GD: Trying to center text but it is showing up horizontally off-center

The PHP code below is supposed to center the letter "M" vertically and horizontally. Vertically it is perfectly centered, but horizontally it is off.
What is really strange is that the offset appears correct, but it seems to be placed at a different coordinate then what I am telling it. (Correct starting X offset should be 10, but it appears to be placed after 16 pixels in).
<?php
header('Content-Type: image/png');
$image = imagecreatetruecolor(100, 400);
$font_size = 92;
$font = "RobotoCondensed-Bold.ttf"; // FILE PATH TO FONT
$angle = 0;
$text = "M";
$red = imagecolorallocate($image, 255, 0, 0);
$white = imagecolorallocate($image, 255, 255, 255);
// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);
$text_bound = imageftbbox($font_size, $angle, $font, $text);
//Get the text upper, lower, left and right corner bounds
$lower_left_x = $text_bound[0];
$lower_left_y = $text_bound[1];
$lower_right_x = $text_bound[2];
$lower_right_y = $text_bound[3];
//$upper_right_x = $text_bound[4];
$upper_right_y = $text_bound[5];
//$upper_left_x = $text_bound[6];
//$upper_left_y = $text_bound[7];
//Get text Width and text height
$text_width = $lower_right_x - $lower_left_x; //or $upper_right_x - $upper_left_x
$text_height = $lower_right_y - $upper_right_y; //or $lower_left_y - $upper_left_y
//Get the starting position for centering
$start_x_offset = ($image_width - $text_width) / 2;
$start_y_offset = ($image_height + $text_height) / 2;
// Add text to image
imagettftext($image, $font_size, $angle, $start_x_offset, $start_y_offset, $red, $font, $text);
// Debug stats
$debug_text = "text_width:[" . $text_width . "]\n";
$debug_text .= "text_height:[" . $text_height . "]\n";
$debug_text .= "start_x_offset:[" . $start_x_offset . "]\n";
$debug_text .= "start_y_offset:[" . $start_y_offset . "]\n";
imagettftext($image, 8, 0, 0, 300, $white, $font, $debug_text);
imagepng($image);
imagedestroy($image);
?>

PHP GD center multiple lines (dynamically text)

Im drawing a dynamically text on a image centersized with GD library.
Whats the best way to align all lines center?
<?php
function imagettfstroketext(&$image, $size, $angle, $x, $y, &$textcolor, &$strokecolor, $fontfile, $text, $px) {
for($c1 = ($x-abs($px)); $c1 <= ($x+abs($px)); $c1++)
for($c2 = ($y-abs($px)); $c2 <= ($y+abs($px)); $c2++)
$bg = imagettftext($image, $size, $angle, $c1, $c2, $strokecolor, $fontfile, $text);
return imagettftext($image, $size, $angle, $x, $y, $textcolor, $fontfile, $text);
}
$image = "12.png";
$font = "./impact.ttf";
$font_size = "50";
$image_2 = imagecreatefrompng($image);
$black = imagecolorallocate($image_2, 255,255,255);
$black2 = imagecolorallocate($image_2, 0,0,0);
$image_width = imagesx($image_2);
$image_height = imagesy($image_2);
$margin = 35;
$text = "This is the Text. It is dynamically long. This text will be split using the function under this text.";
//explode text by words
$text_a = explode(' ', $text);
$text_new = '';
foreach($text_a as $word){
//Create a new text, add the word, and calculate the parameters of the text
$box = imagettfbbox($font_size, 0, $font, $text_new.' '.$word);
//if the line fits to the specified width, then add the word with a space, if not then add word with new line
if($box[2] > $image_width - $margin*2){
$text_new .= "\n".$word;
} else {
$text_new .= " ".$word;
}
}
$text_box = imagettfbbox($font_size,0,$font,$text_new);
$text_width = $text_box[2]-$text_box[0]; // lower right corner - lower left corner
$text_height = $text_box[3]-$text_box[1];
$x = ($image_width/2) - ($text_width/2);
$y = ($image_height/2) - ($text_height/2);
$font_color = imagecolorallocate($image_2, 255, 255, 255);
$font_color2 = imagecolorallocate($image_2, 0, 0, 0);
$stroke_color = imagecolorallocate($image_2, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$grey = imagecolorallocate($im, 175, 175, 175);
imagettfstroketext($image_2, $font_size ,0,$x,$y,$font_color, $stroke_color, $font, $text_new, 0);
header ("Content-type: image/png");
imagejpeg($image_2, "../img/output.png");
imagedestroy($image_2);
?>
This is what it looks right now:
This is what it should look like:
Using three times "imagettfstroketext" with adding "$y+50" would do the trick but the text is dynamic.
Any suggestions?
best regards
I would create a temporary image on one line, storing the accumulated length in an array. Then determine exactly which words fit on a line, and the offset to center each line. Then create the image.
Alternatively you can create separate images for each line, then combine them with the right offset.

Photo Frame Sample - Light Red Shade and Text Align Center

I am trying to create a photo frame where there will be a light red shade and a text aligned center. I am taking the actual size of the images and then trying to create the new image programmatically with the frame. Below is a sample that I did so far:
In the image, there is a white border that I've used for demonstration purpose. I want the light red shade should not go over the white border and the text should be exactly in the middle for every image. As I am working with the actual image size, the shade and text does not remain in the specific position. In some images, the light red shade and text does not show up. I did the following code to make it work but seem like missing something:
$size = getimagesize($file_tmp); //Gets the image file size
$width = $size[0];
$height = $size[1];
$images_orig = imagecreatefromjpeg($file_tmp); //Creates jpeg image from tmp file location
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = imageCreateTrueColor($width, $height);
$color = imagecolorallocate($images_fin, 255, 255, 255);
$lightRed = imagecolorallocatealpha($images_fin, 255, 0, 0, 100);
$black = imagecolorallocate($images_fin, 0, 0, 0);
$text = 'I am from China';
$font = 'MyriadPro-Light.ttf';
$positions_redline = ($height / 4)*3;
ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width, $height, $photoX, $photoY);
Imagefilledrectangle($images_fin, 0, $positions_redline, $width, $height, $lightRed);
$font_size = 10;
/*Starts - This is what I tried to fit the text into the image specifically in the center*/
$bbox = imagettfbbox($font_size, 0, $font, $text);
$tbwidth = $bbox[2];
$factor = round(($width / $tbwidth), 0, PHP_ROUND_HALF_DOWN);
$newFontSize = $font_size * $factor;
/*Finishes - This is what I tried to fit the text into the image specifically in the center*/
print_r($bbox[2]);
print_r("<br/>".$factor);
// Get your Text Width and Height
$text_width = $bbox[2] - $bbox[6];
$text_height = $bbox[3] - $bbox[7];
// Calculate coordinates of the text
$x = ($photoX / 2) - ($text_width / 2);
$y = (($height - $positions_redline) / 2) - ($text_height / 2);
Imagettftext($images_fin, $newFontSize, 0, $x, $y + $positions_redline, $color, $font , $text); //Trying to write text and align it center here
$new_images = 'testImageResult.jpg';
ImageJPEG($images_fin,"Images/".$new_images);
Try this source
$file_tmp = '/var/www/html/testGuzzle/testImage.jpg';
$size = getimagesize($file_tmp); //Gets the image file size
$width = $size[0];
$height = $size[1];
$images_orig = imagecreatefromjpeg($file_tmp); //Creates jpeg image from tmp file location
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = ImageCreateTrueColor($width, $height);
$color = imagecolorallocate($images_fin, 255, 255, 255);
$lightRed = imagecolorallocatealpha($images_fin, 255, 0, 0, 100);
$black = imagecolorallocate($images_fin, 0, 0, 0);
$text = 'Im from VietNam';
$font = '/var/www/html/testGuzzle/OpenSans-SemiboldItalic.ttf';
$positions_redline = ($height/4)*3;
ImageCopyResampled($images_fin, $images_orig, 0, 0, 0, 0, $width, $height, $photoX, $photoY);
Imagefilledrectangle($images_fin, 0, $positions_redline, $width, $height, $lightRed);
$font_size = 20;
$bbox = imagettfbbox($font_size, 0, $font, $text);
print_r($bbox);
// Get your Text Width and Height
$text_width = $bbox[2]-$bbox[0];
$text_height = $bbox[7]-$bbox[1];
// Calculate coordinates of the text
$x = ($photoX/2) - ($text_width/2);
$y = ($height-$positions_redline)/2) - ($text_height/2);
Imagettftext($images_fin, 40, 0, $x, $y+$positions_redline, $color, $font , $text); //Trying to write text and align it center here
$new_images = 'testImageResult.jpg';
ImageJPEG($images_fin,"/var/www/html/testGuzzle/".$new_images);

Barcode generated does not get read

I use the following code to create an EAN13 barcode. The barcode is created without any issues, but when I scan it it is not recognized.
What is the problem?
include('php-barcode.php');
$font = 'fonts/GSMT.TTF';
$fontSize = 16; // GD1 in px ; GD2 in point
$marge = 10; // between barcode and hri in pixel
$x = 80; // barcode center
$y = 80; // barcode center
$height = 50; // barcode height in 1D ; module size in 2
$width = 2; // barcode height in 1D ; not use in 2D
$angle = 0;
$code = "111110001001"; // barcode, of course ;)
$type = "ean13"; //
$im = imagecreatetruecolor(180, 180);
$black = ImageColorAllocate($im,0x00,0x00,0x00);
$white = ImageColorAllocate($im,0xff,0xff,0xff);
imagefilledrectangle($im, 0, 0, 180, 180, $white);
$data = Barcode::gd($im, $black, $x, $y, $angle, $type, array('code'=>$code), $width, $height);
if ( isset($font) ){
$box = imagettfbbox($fontSize, 0, $font, $data['hri']);
$len = $box[2] - $box[0];
Barcode::rotate(-$len / 2, ($data['height'] / 2) + $fontSize + $marge, $angle, $xt, $yt);
imagettftext($im, $fontSize, $angle, $x + $xt, $y + $yt, $black, $font, $data['hri']);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);

center text in image

So I have an image, and I am writing text and a color box onto the image. It works but it's being added to the image in the top right corner, but I need it in the center of the image. I tried changing the x and y variables, but it only moves the text and not the white box.
Here is code
$image_filepath = './kenshin.jpg';
saveImageWithText("Welcome to Eureka!", $color, $image_filepath);
function saveImageWithText($text, $color, $source_file) {
$public_file_path = '.';
// Copy and resample the imag
list($width, $height) = getimagesize($source_file);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($source_file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
// Prepare font size and colors
$text_color = imagecolorallocate($image_p, 0, 0, 0);
$bg_color = imagecolorallocate($image_p, 255, 255, 255);
$font = $public_file_path . '/arial.ttf';
$font_size = 12;
// Set the offset x and y for the text position
$offset_x = 0;
$offset_y = 20;
// Get the size of the text area
$dims = imagettfbbox($font_size, 0, $font, $text);
$text_width = $dims[4] - $dims[6] + $offset_x;
$text_height = $dims[3] - $dims[5] + $offset_y;
// Add text background
imagefilledrectangle($image_p, 0, 0, $text_width, $text_height, $bg_color);
// Add text
imagettftext($image_p, $font_size, 0, $offset_x, $offset_y, $text_color, $font, $text);
// Save the picture
imagejpeg($image_p, $public_file_path . '/output.jpg', 100);
// Clear
imagedestroy($image);
imagedestroy($image_p);
};
Here is output
Try this. It will help you…
<?php
$img = imagecreatefromjpeg("girl-hugging-the-globe.jpg"); // image.jpg is the image on which we are going to write text ,you can replace this iamge name with your
if(!$img) die("Unabe to load image");
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$width = 600;// it will store width of image
$height = 100; //it will store height of image
$fontsize = 6; // size of font
$text = "Block Prints Online"; // Define the text
$pos = ( $width - imagefontwidth($fontsize)*STRLEN($text) );// calculate the left position of the text:
imagestring($img, $fontsize, 200, 150, $text, $red);
header('Content-type: image/jpeg');
imagejpeg($img);//it will output a jpeg image
imagedestroy($img);//it will destroy $img*/
?>

Categories