PHP imagettftext always drawing black - php

Basically when I draw text it's ending up black like this: http://i.stack.imgur.com/z675F.png
Instead of the color I'm allocated in PHP and the function.
Code:
$finalImage = imagecreatefrompng($imageFile);
$logo = imagecreatefrompng($logoImage);
imagecopy($finalImage, $logo, $logoPosition['x'], $logoPosition['y'], 0, 0, imagesx($logo), imagesy($logo));
$font = "arial.ttf";
$fontSize = 10;
$yOffSet = 15;
$white = imagecolorallocate($finalImage, 255, 255, 255);
foreach($pixelArray as $key => $x) {
foreach($valueArray[$key] as $valueText) {
imagettftext($finalImage, $fontSize, 0, $x, $yOffSet, $white, $font, $valueText);
$yOffSet += 15;
}
$yOffSet = 15;
}
if($miscText != null) {
foreach($miscText as $key => $text) {
imagettftext($finalImage, $fontSize, 0, $text['x'], $text['y'], $white, $font, $text['text']);
}
}
imagepng($finalImage,$saveFileName.".png");
imagedestroy($finalImage);
It was working before, but then it just stopped and I have no clue why. It was after I changed the source image (Was generating fine) and I hadn't touched the code. I've tried all sorts of things with changing the colors, but I can't get it to display in anything other then black.

Fixed it by changing imagecolorallocate to imagecolorclosest since I already some white text on a logo I copy in:
// imagecolorallocate....
$white = imagecolorclosest($im, 255, 255, 255);

Have you checked if the imagecolorallocate() function is returning boolean false, as it will if the allocation fails? If the $finalImage .png is 8bit, and your pure white color isn't in the source image's palette, this call will fail. You do say you changed the source image, so this is most likely why it's broken now.
$white = imagecolorallocate($finalImage, 255, 255, 255);
if ($white === FALSE) { // note the === -> strict type comparison
die("Failed to allocate color 255/255/255")
}
The function will also simply return a number representing the color triplets, in this case it would 0xFFFFFF. You can try passing that into the imagegetttftext() call directly, see if that helps.

Use imagecreatetruecolor() to allocate the color:
$width = 500; //whatever width you need
$height = 200; //whatever height you need
$white = imagecolorallocate(imagecreatetruecolor($width, $height), 255, 255, 255);
That worked for me.

Related

imagejpeg creating black image

I know it is an old question but I am not able to solve it. Here is my code
function add_ZK_mark($inputfile, $outputfile) {
$im = #imagecreatefromjpeg($inputfile);
$bg = #imagecolorallocate($im, 255, 255, 255);
$textcolor = #imagecolorallocate($im, 0, 0, 255);
list($x, $y, $type) = getimagesize($inputfile);
#imagejpeg($im, $outputfile);
#imagedestroy($im);
}
I am getting jpeg image type everytime. Using signature.js to get image in jpeg format.
Thanks

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

PHP: Function to change text to PNG image with transparency

I am trying to change a section of text into an image. I can't figure out what is wrong with my code and also how to make it transparent. Here is what I have so far:
<?PHP
function fsrep_imageaddress($address, $listingid) {
$font_size = 4;
$width = imagefontwidth($font_size)*strlen($address);
$height = imagefontheight($font_size);
$img = imagecreate($width,$height);
$bg = imagecolorallocate($img, 25, 25, 25);
$color = imagecolorallocate($img, 255, 255, 255);
$len = strlen($address);
$ypos = 0;
for($i=0;$i<$len;$i++){
$xpos = $i * imagefontwidth($font_size);
imagechar($img, $font_size, $xpos, $ypos, $address, $color);
$address = substr($address, 1);
}
imagepng($img, ABSPATH.'wp-content/uploads/fsrep/houses/address-'.$listingid.'.png',100);
imagedestroy($img);
}
fsrep_imageaddress(Just Testing, 12)
?>
Why is it not working?
If you look in the error log, you'll see you need to put "Just Testing" in quotes (thanks #scrowler!) in the function call. Then you'll get an error that imagepng takes a quality level of 0 (no compression) to 9 (max). You have 100! Here, I set it to 5 (medium compression).
imagepng($img, ABSPATH.'wp-content/uploads/fsrep/houses/address-'.$listingid.'.png',5);
How do I set a transparent background?
There's a weird thing with palette images (ie those created with imagecreate). The first colour allocated is set as the background, and can't be transparent - so you need to create a dummy color and then convert it to transparent.
// after this line
$bg = imagecolorallocate($img, 25, 25, 25);
// add this
imagecolortransparent($img, $bg);
Result
I made these changes and changed the text to red (255,0,0) for readability and got this:

Adding color to a white icon in PHP GD

I have a white icon (256x256) with a transparent background. Somehow, I want to be able to change the white icon, which has some transparent pixels in it (for anti-aliasing), to any RGB color.
I have tried using the following function but
imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)
Is there any way to do this in PHP GD? What functions can I look into?
I just created the following code and it works wonders.
Beware: If you set $backgroundTransparent to false, the image may lose quality when the background is painted under it.
<?php
$width = 256;
$height = 256;
$backgroundColor = array(0, 255, 0);
$backgroundTransparent = true;
$icon = imagecreatefrompng('Access-New.png');
imagealphablending($icon, false);
imagesavealpha($icon, true);
imagefilter($icon, IMG_FILTER_BRIGHTNESS, -255);
imagefilter($icon, IMG_FILTER_COLORIZE, 255, 0, 0);
if($backgroundTransparent == false) {
$background = imagecreatetruecolor($width, $height);
imagefill($background, 0, 0, imagecolorallocate($background, $backgroundColor[0], $backgroundColor[1], $backgroundColor[2]));
imagealphablending($icon, true);
imagecopy($background, $icon, 0, 0, 0, 0, $width, $height);
imagepng($background, NULL, 0, PNG_NO_FILTER);
}
else {
imagepng($icon, NULL, 0, PNG_NO_FILTER);
}
header("Content-type: image/png");
imagedestroy($background);
?>

turning text into image - PHP/GD - save image

I'm using this script to simply create an image from text. What I would like to know is how to save the image instead of printing straight to browser;
// an email address in a string
$string = $post[$key];
// some variables to set
$font = 4;
$width = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);
// lets begin by creating an image
$im = #imagecreatetruecolor ($width,$height);
//white background
$background_color = imagecolorallocate ($im, 255, 255, 255);
//black text
$text_color = imagecolorallocate ($im, 0, 0, 0);
// put it all together
$image = imagestring ($im, $font, 0, 0, $string, $text_color);
I know its probably just one line of code at the end but im not sure which GD function to use.
Any help would be much appreciated, Regards, Phil.
EDIT:
I have tried the following but just get a balnk black box;
// an email address in a string
$string = $post[$key];
// some variables to set
$font = 4;
$width = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);
// lets begin by creating an image
$im = #imagecreatetruecolor ($width,$height);
//white background
$background_color = imagecolorallocate ($im, 255, 255, 255);
//black text
$text_color = imagecolorallocate ($im, 0, 0, 0);
// put it all together
imagestring ($im, $font, 0, 0, $string, $text_color);
imagepng($im, 'somefile.png');
imagedestroy($im);
Pass a filename to the appropriate image-generating image*() function:
imagepng($image, 'somefile.png');
Look at here http://www.php.net/manual/en/function.imagepng.php
take a look at imagepng() (or imagegif, imagejpeg...) - if you add a filename as second parameter, the image is saved as file.

Categories