Adding Text with GD Lib - php

I have been ripping my hair out with this and have tried many many solutions on here to no avail.
I am trying to add some text to an image, but all it is doing is showing my background image, is there anything glaringly obvious that I'm doing wrong here?
Thanks in adcance
<?
header('Content-Type: image/jpeg');
$fbid = $_POST['fbid'];
$background_img = $_POST['background'];
$message = $_POST['text'];
$ts = $_POST['ts'];
$filename = $fbid . "-" . $ts . ".jpg";
$image_canvas = imagecreatetruecolor(640,400);
$background = imagecreatefromjpeg($background_img);
$overlay = imagecreatefrompng("../images/image-overlay.png");
imagecopyresampled($background, $overlay, 0, 0, 0, 0, imagesx($overlay), imagesy($overlay), imagesx($overlay), imagesy($overlay));
imagefilledrectangle($image_canvas, 0,0,150,30, $background);
$white = imagecolorallocate($background, 255, 255, 255);
imagettftext($image_canvas, 25, 0, 50, 50, $white, "arial.TTF", $message);
imagejpeg($background,"../created/" . $filename, 100);
imagedestroy($background);

You're missing the canvas. Start the build with imageCreateTrueColor.
$imageCanvas = imageCreateTrueColor($width, $height);
//your code
$background = imagecreatefromjpeg($background_img);
//more of your code
imagefilledrectangle($imageCanvas, 0, 0, 150, 30, $background);
//now do the same for the text only us imag
imagettftext($imageCanvas, 25, 0, 50, 50, $white, "arial.TTF", $message);
Your merging the jpeg and the text elements on the $imageCanvas.

Have a look at this. It works, and the link to the page is below. Based on your original post, I believe this is what your looking for.
/* first composite the canvas with the background */
$background_img="../img/adfuba_october.png";
$compositeString = "composite.png";
list($width,$height) = getimagesize($background_img);
$image_canvas = imagecreatetruecolor($width,$height);
$background = imagecreatefrompng($background_img);
imagecopyresampled($image_canvas,$background,0,0,0,0,$width,$height,$width,$height);
/* now add the text */
$fontPath = "path/to/your/fontFile/ARIAL.TTF";
$fontSize = 24;
$percent = 0.25;
$txt_x = abs($width*$percent);
$txt_y = abs($height*$percent);
$color = "008844";
$message = "This is User Text";
imageTTFtext($image_canvas, $fontSize, 0, $txt_y, $txt_y, $color, $fontPath, $message);
/* now generate the file */
imagepng($image_canvas, $compositeString, 0) or die("error saving png");
?>
<p>This is a composite image:<br><img src="<?php echo $compositeString;?>"></p>
You can see the composite image here.
Couple things to keep in mind. The path to your TrueType font face should be absolute even if the TrueType font file is located in the same directory as your script.
Also, the canvas is your background object, then you layer images or text over top the canvas.
Finally, (and you may have figured this out) your layered elements are order dependent form canvas to text. Meaning canvas -> background -> another graphic -> then the text. Otherwise, you could end up covering up an element you meant to render in front. Hope that helps.

Related

imagejpeg not working when used in Wordpress

Good day. Why is that when I try to run my code on an external page, it works perfectly. But when I used wordpress to add it on my page, it gives me strange errors. Why is that and how do I fix that?
code:
<?php
// (A) OPEN IMAGE
$img = imagecreatefromjpeg('https://images.unsplash.com/photo-1550684376-efcbd6e3f031?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80');
// (B) WRITE TEXT
$white = imagecolorallocate($img, 255, 255, 255);
$txt = "sad";
$font = realpath('arial.ttf');
//(IMAGE, FONT SIZE, TILT ANGLE, X, Y, COLOR, FONT, TEXT)
imagettftext($img, 12, 0, 253, 234, $white, $font, $txt);
// (C) OUTPUT IMAGE
header('Content-Type: image/jpeg');
imagejpeg($img);
// OR SAVE TO A FILE
// THE LAST PARAMETER IS THE QUALITY FROM 0 to 100
imagejpeg($img, "test.jpg", 100);
?>
Here's the result I got when trying it on my wordpress page:
Image here
The issue is that you are running this in a shortcode and change the header of the output, that you already created, namely the page. It depends on what you want to do, if you want to display the image in the site:
ob_start();
imagejpeg( $img, NULL, 100 );
imagedestroy( $img );
$i = ob_get_clean();
echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>";

Adding text to images with PHP

I'm running into some issues with adding custom text to an image, what I am try to do is have 3 lines of text that is centered. However the centered text is on the right side of the image, not in the center of the image. This is what I have so far with text added, but I need to have the text aligned center with the line shown on the image.
// Variables
$img = LoadJpeg('img/custom-image.jpg');
$orig_width = imagesx($img);
$orig_height = imagesy($img);
$width = 2500;
$font_path = 'font/ArialBlack.ttf';
$text_line_1 = $_GET['series'];
$text_line_2 = $_GET['custom'];
$text_line_3 = $_GET['model'];
// Calc the new height
$height = (($orig_height * $width) / $orig_width);
// Create new image to display
$new_image = imagecreatetruecolor($width, $height);
// Create some colors
$white = imagecolorallocate($new_image, 255, 255, 255);
// Create new blank image with changed dimensions
imagecopyresized($new_image, $img,0, 0, 0, 0, $width, $height, $orig_width, $orig_height);
// Add text to image
imagettftext($new_image, 13,0, 2150,72, $white, $font_path, $text_line_1);
imagettftext($new_image, 13,0, 2150,92, $white, $font_path, $text_line_2);
imagettftext($new_image, 13,0, 2150,112, $white, $font_path, $text_line_3);
// Print image
imagejpeg($new_image);
imagejpeg($img);
imagedestroy($img);
I'm also wanting to make the width variable from the url, I can do but I'm not sure how to resize the text to match the resized image. Any assistance would be greatly appreciated.
Current Placement of Text
What I am wanting
You want to use imagettfbbox() for this to calculate the horizontal offset:
$bbox = imagettfbbox(13, 0, $font_path, $text_line_1);
$xOffset = ($bbox[2] - $bbox[0]) / 2;
Now just subtract the offset from your desired position and you are good to go.

Is it possible to swipe a specific color with an Image using PHP GD Library?

I would like to know if is it possible to swipe a specific color with an Image.
I would use this if I wanted to change the color:
$imgname = "http://i.imgur.com/a94EGj9.png";
$im = imagecreatefrompng ($imgname);
imagetruecolortopalette($im,false, 255);
$index = imagecolorclosest ( $im, 21,194,37 ); // get color
imagecolorset($im,$index,255,255,255); // SET NEW COLOR
$time = time();
$imgname = "img".$time.".png";
imagegif($im, $imgname );
imagedestroy($im);
echo "<img src='".$imgname."' width='500' height='500' >";
But I want to change the background with an image.
Example, I downloaded a image of a room, and I painted the ground.
http://i.imgur.com/a94EGj9.png
I would like to know if I can remove the green ground and insert an image in there, like this:
http://i.imgur.com/sXWXkJ5.jpg
Is it possible to do that?
Thank you.
You probably want to use imagecopymerge, with 100 alpha.
$background_layer = imagecreatefrompng('image_background.png');
$imgname = "http://i.imgur.com/a94EGj9.png";
$im = imagecreatefrompng ($imgname);
$color = imagecolorallocate($im, 21, 194, 37);
imagecolortransparent($im, $color);
imagecopymerge($background_layer, $im, 0, 0, 0, 0, imagesx($im), imagesy($im), 100);
header("Content-Type: image/png");
imagepng($background_layer);

How to write text to images with different sizes using PHP GD

I'm creating images with different sizes. How can I write text on those images so that the texts always fit to the images?
$text = "some text as example";
$font = "arialbd.ttf"
$fontsize = 26;
offset_x = 0;
offset_y = 0;
$image01 = imagecreate( 1120 , 900 );
$image02 = imagecreate( 400 , 300 );
$image03 = imagecreate( 1120 , 900 );
I know that there is the imagefttext function that can apply text to the images but with that function I can only change the font size to make the text bigger. How can I find out that it fits into my image?
If you are looking to scale the font size so that text string fills the image width, try this.
Using imagettfbbox, determine the current text box width:
$bbox = imagettfbbox($fontsize,0,$fontpath,$string);
$tbwidth = $bbox[2];
Then divide the image width by the $tbwidth to get a factor
$factor = round(($imgwidth / $tbwidth), 0, PHP_ROUND_HALF_DOWN); //ie. 800/240=3
Multiple the $factor by you $fontsize to get an approximate increase.
$newfontsize = $fontsize * $factor; //ie. 12(pt) * 3 = 36
Keep in minds, if you're using GD 2.0, fontsize is in Points and not pixels. Your algorithm is going to calculate the difference between your default font size text box (expressed as a text box width) and the image width.
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(800, 600);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $white);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font_file = 'arial.ttf';
$font_size = '15';
$bbox = imageftbbox($font_size, 0, $font_file, $text);
$width = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];
// Add the text
imagettftext($im, $font_size, 0, 10, 20, $black, $font_file, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
I recently came across the same situation with transparent backgrounds but the current examples are either not a solution but clues or a solution that doesn't work, so hereby a combined and working solution if anyone need it.
function imagecreater($width = 600, $height = 600) {
//Create an empty transparent image
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefill($img, 0, 0, $transparent);
//Text information
$text = "some text as example";
$font = "arialbd.ttf"
$fontsize = 26; //default font to be altered later
//simulate a complete text box and get the width
$bbox = imageftbbox($fontsize, 0, $font, $text);
$tbwidth = $bbox[2];
//Calculate different between our transparent image and text box
//I've added a little padding (20px) since the text sometimes crossing the edge..
$factor = (($width - 20) / $tbwidth);
//Alter font size with difference to fit fully image
$newfontsize = $fontsize * $factor;
//Find the horisontal center
$bbox = imageftbbox($newfontsize, 0, $font, $text);
$newheight = ($height / 2) + (($bbox[3] - $bbox[7]) / 2);
//Set Color of text
$color = imagecolorallocate($img, 200, 0, 0);
//Produce our image
imagettftext($img, $newfontsize, 0, 0, $newheight, $color, $font, $text);
//Copy image to file and free the cached image
$target = "testimage.png";
imagepng($img, $target);
imagedestroy($img);
}
As rwhite35 mentioning here, please keep in mind that GD 2.0 write font size is in points and not pixels.
Use the imageftbbox function to get the size of the bounding box of the text. You can then adjust the text size to fit the size of the image exactly.
http://www.php.net/manual/en/function.imageftbbox.php

Empty space getting filled with black after GD imagecopy but only in some scenarios

I am experiencing an issue where I am allowing the user to resize images in a container and then need to create a resulting image that is the size of the container but with the image scaled and adjusted as per the users choices.
So for example say the container is 400 x 200 and the user wants to be able to put in a logo that is 600 x 100 they may wish to shrink the logo so it fits and leave space at the top and bottom. I need to be able to save that as an image that is 400x200 with the appropriate gaps at the top and bottom.
What I have found though is that if the image content (the logo in this example) extends beyond BOTH the top and the right of the container everything is fine OR if it DOESNT extend beyond either it is fine but if it extends beyond one and not the other then I get black fill- or something like that- see examples below...
Below are some examples of the results and this is the code I am using...
$cropped = wp_imagecreatetruecolor( $frame_w, $frame_h);
$backgroundColor = imagecolorallocatealpha($cropped, 0, 0, 0, 127);
//imageantialias( $cropped, true );
//if $img_y or $img_x are negative we need to apply the value to $img_x and $img_y
//if $img_y or $img_x are positive we need to apply the value to $dest_x and $dest_y
$dest_x = strstr($img_x,'-') ? 0 : abs($img_x);//if neg is true = 0 else offset inside
$dest_y = strstr($img_y,'-') ? 0 : abs($img_y);
$img_x = strstr($img_x,'-') ? abs($img_x) : 0;//if neg is true offset outside else 0
$img_y = strstr($img_y,'-') ? abs($img_y) : 0;
$img_w = $img_w > $frame_w ? $frame_w : $img_w;
$img_h = $img_h > $frame_h ? $frame_h : $img_h;
imagecopy( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $img_w, $img_h);
//imagecopymerge( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $img_w, $img_h,100);
//imagecopyresampled( $cropped, $resized, $dest_x, $dest_y, $img_x, $img_y, $frame_w, $frame_h, $img_w, $img_h );
imagefill($cropped, 0, 0, $backgroundColor);//putting this after the copy makes any black borders transparent again unless $resized does not extend beyond both dimensions
Examples
Image does not extend beyond top or beyond right (fine)
Image extends beyond bottom but not right (not fine)
Image extends beyond both (fine)
Image extends beyond right but not bottom (not fine)
Image Extends beyond neither (fine)
I have been literally tearing my hair out trying to fix this and tried every possible combination of imagesavealpha, imagecopymerged, imagecolorallocatealpha, imagealphablending etc I can think of but nothing seems to fix this...
So is this a bug/limitation of GD? Or can someone out there come to my rescue!
I don't know if this will help you, but I had an issue with this earlier today. The box expands but the area was black. Here's my code (which fixes it):
<?php
function createImage($text)
{
// Adds an extra space to fill underline
$text = " $text";
// Adds one line at the end
$text .= "\n";
// Wrap the text to fit the image
$text = wordwrap($text, 40, "\n");
// Count new lines
$newlines = substr_count($text, "\n");
// Count how long to expand
if($newlines == 0)
{
$height = 30;
}
else
{
$height = 30*$newlines-$newlines*5;
}
putenv('GDFONTPATH=' . realpath('.'));
header('Content-Type: image/png');
// Adding underline
$e = explode('<', $text);
for($i=0;$i<count($e);$i++)
{
$e[$i] = implode('̲', str_split($e[$i]));
}
// Creating image
$text = implode(' ', $e);
$im = imagecreatetruecolor(315, $height);
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
$purple = imagecolorallocate($im, 97, 26, 139);
imagefilledrectangle($im, 0, 0, 399, $height, $white);
$font = 'arialbd.ttf';
imagettftext($im, 11, 0, 10, 20, $purple, $font, $text);
imagepng($im);
imagedestroy($im);
}
createImage("asbdasddsa");
?>
i think this will happen only for PNG check with other formats
I'm not sure if this is an actual answer since it is basically 'Use ImageMagick' but anyway for those for whom ImageMagick is an option the code below might help them achieve the same thing as I was trying to above... Basically ImageMagick seems far superior to GD, no borders around rotated images, no hassles with transparency, no onwanted black fill, clearer resizing if you are enlarging...
$img_x = -50; //left offset of the image within the frame
$img_y = 50; //top offset of the image within the frame
$img_w = 400; //width of the image to be put in the frame
$img_h = 200; // height of the image to be put in the frame
$angle = 45; //rotation to be applied to the image before it is put into the frame
$frame_w = 300; //width of the frame the image is going into
$frame_h = 300; //height of the frame the image is going into
$img_path = 'path/to/image/file.jpg';
$image = new Imagick( $img_path );
$size = $image->getImageGeometry();
$orig_w = $size['width']; $orig_h = $size['height'];
$image->scaleImage( $img_w, $img_h );
//rotate if necessary
if($angle)
{
$image->rotateImage( new ImagickPixel('none'), $angle );
$size = $image->getImageGeometry();
$img_w = $size['width']; $img_h = $size['height'];
}
//composite into frame
//in imagemagick we create an image that is the size of the frame and make it transparent
$frame = new Imagick();
$frame->newImage($frame_w, $frame_h, new ImagickPixel("none"));
//then we composite the image itself into this with the respective offset values
$frame->compositeImage( $image, Imagick::COMPOSITE_DEFAULT, $img_x, $img_y );
//save it
$destfilename = "{$dir}/{$name}-{$img_suffix}.{$ext}";
$frame->writeImage($destfilename);
$frame->clear();
$frame->destroy();
$image->clear();
$image->destroy();
The above code produces this...yay!

Categories