write text to an image - php

I have an image on my server and I want to write text to it. Like a watermark. I am able to write text to the image, but I want to add a background to the text so it's easy to read. Here is what I have so far.
header("Content-type: image/jpeg");
$imgPath = 'pic.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 224, 73, 87);
$string = "Please type the word in the circle.";
$fontSize = 8;
$x = 25;
$y = 200;
imagestring($image, $fontSize, $x, $y, $string, $color);
imagejpeg($image);

in this class you need to have a background base.png and font arial.ttf you can have a diffident font but must be a ttf .if you want to have diffident font format you must make change on code
class SecurityImg{
static function Image_Create($basename){//Create image
$im =imagecreatefrompng ($basename);
//only replace imagecreatefrompng with imagecreatefromjpeg for open jpg instead of png
return($im);
}
static function PutTextOnImage($text,$baseimage,$angel,$xi,$yi){
// Create some colors
$text_color= imagecolorallocate($baseimage, 255, 50, 150);
// Replace path by your own font path
$font = 'arial.ttf';
// Add the text
imagettftext($baseimage, 15, $angel, $xi, $yi, $text_color, $font, $text);
return($baseimage);
}
static function Create($imgbase,$TEXT){
$ifp=self::Image_Create($imgbase);
$im=self::PutTextOnImage($TEXT,$ifp,0,10,20);
return($im);
}
}
$Securityimg=new SecurityImg();
$im=$Securityimg->Create("base.png","test");
// Output the image
// Set the content-type
header('Content-Type: image/jpeg');
imagejpeg($im);
// Using imagepng() results in clearer text compared with imagejpeg()
imagedestroy($im);

Check out this :
<?php
$stamp = imagecreatefrompng('stampimg.png');
$im = imagecreatefrompng('mainimage.png');
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
$imgx = imagesx($im);
$imgy = imagesy($im);
$centerX=round($imgx/2);
$centerY=round($imgy/2);
imagecopy($im, $stamp, $centerX, $centerY, 0, 0, imagesx($stamp), imagesy($stamp));
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

Related

Watermarking: Display the same text on multiple parts of the image

I want to add a text to a image. The text should be displayed in multiple areas of the image (not just one).
For example I want to watermark with a text stack. Stack should be displayed in the image at least 8 times in different areas in the image.
I just learned about imagestring() and imagettftext(), but these two only displays my text on a single spot.
Image is not fixed size, so i cannot specify exact and multiple location in advance. It should work on all sizes of images
<?php
/*
image.php
*/
header("Content-type: image/jpeg");
$imgPath = 'olximage.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = "stack overflow";
$fontSize = 3;
$x = 15;
$y = 185;
imagestring($image, $fontSize, $x, $y, $string, $color);
$x = 15;
$y = 175;
imagestring($image, $fontSize, $x, $y, $string, $color);
imagejpeg($image);
?>
Thanks in advance
For example:
<?php
/*
image.php
*/
header("Content-type: image/jpeg");
$imgPath = 'olximage.jpg';
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = "stack overflow";
$fontSize = 3;
$imageHeight = imagesy($image);
$distanceY = 10;
$maxImageStrings = max(8, $imageHeight / $distanceY);
$x = 15;
for ($i = 0; $i < $maxImageStrings; $i++) {
$y = $i * $distanceY;
imagestring($image, $fontSize, $x, $y, $string, $color);
}
imagejpeg($image);
You can finetune calculations for your needs.
I'm using Imagick extension for same. If you want to go with this then follow detail:
PHP:
// Create objects
$image = new Imagick('image.png');
$watermark = new Imagick();
// Watermark text
$text = 'Copyright';
// Create a new drawing palette
$draw = new ImagickDraw();
$watermark->newImage(140, 80, new ImagickPixel('none'));
// Set font properties
$draw->setFont('Arial');
$draw->setFillColor('grey');
$draw->setFillOpacity(.5);
// Position text at the top left of the watermark
$draw->setGravity(Imagick::GRAVITY_NORTHWEST);
// Draw text on the watermark
$watermark->annotateImage($draw, 10, 10, 0, $text);
// Position text at the bottom right of the watermark
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);
// Draw text on the watermark
$watermark->annotateImage($draw, 5, 15, 0, $text);
// Repeatedly overlay watermark on image
for ($w = 0; $w < $image->getImageWidth(); $w += 140) {
for ($h = 0; $h < $image->getImageHeight(); $h += 80) {
$image->compositeImage($watermark, Imagick::COMPOSITE_OVER, $w, $h);
}
}
// Set output image format
$image->setImageFormat('png');
// Output the new image
header('Content-type: image/png');
echo $image;
although there are plenty of command-line examples to be found on the ImageMagick website, so that is where we shall begin.

Convert php string to image

I want to convert a php string to an image.
I use this code
header("Content-type: image/png");
$string = '.the_title().';
$font = 5;
$width = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);
$image = imagecreatetruecolor ($width,$height);
$white = imagecolorallocate ($image,255,255,255);
$black = imagecolorallocate ($image,0,0,0);
imagefill($image,0,0,$white);
imagestring ($image,$font,0,0,$string,$black);
imagepng ($image);
imagedestroy($image)
but its shows the_title as text instead of executing the string
Use imagecreatefromstring
$string = '.the_title().';
$data = base64_decode($string);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
Use imagestring like:
<?php
$string = the_title();
$im = imagecreate(150, 20); // image size 150x20px
imagecolorallocate($im, 255, 255, 255); // background white
$text_color = imagecolorallocate($im, 0, 0, 0); // text color black
imagestring($im, 3, 5, 5, $string, $text_color); // append string to image
header('Content-type: image/png'); // filetype
imagepng($im, 'image.png'); // save as image.png
imagedestroy($im); // free up memory

How to convert text to image in PHP with line break?

Currently I am using the PHP code below to convert string text to image with transparent background. Now I need to convert the string text to image with line break, transparent background and also with custom font. Code I am using:
$width = 200;
$height = 40;
$text = "Test text -- line break here -- with line break";
$fontsize = 3;
$img = imagecreate($width, $height);
$black = imagecolorallocate($img, 0, 0, 0);
imagecolortransparent($img, $black);
$color = imagecolorallocate($img, 0, 0, 0);
imagestring($img, $fontsize, 0, 0, $text, $color);
header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
Doing it like this will help you
header("Content-type: image/png");
$str1= 'Test text ';
$str2= 'with line break';
$image= imagecreate(200,40);
$background = imagecolorallocate($image,255,255,255);
$color= imagecolorallocate($image,0,0,0);
imagefill($image,0,0,$background);
imagestring($image,10,5,5,$str1,$color);
imagestring($image,10,5,20,$str2,$color);
imagepng($image);
output look like this

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*/
?>

imagecreatefrompng() + imagettftext() low quality text - how to anti alias

Take the following base image (PNG-24):
We're trying to write text to the image as follows:
<?
ini_set('display_errors', 1);
error_reporting(E_ALL);
//#### Load the base image
$im = imagecreatefrompng("images/SpecialClearanceBlank.png");
imagealphablending($im, false);
imagesavealpha($im, true);
//#### Create the badge
if($im) {
//#### define some colours to use with the image
$white = imagecolorallocate($im, 255, 255, 255);
//#### get the width and the height of the base image
$width = imagesx($im);
$height = imagesy($im);
//#### Define font and text
$font = "/var/www/arial.ttf";
$fontSize = 13;
$angle = 0;
$text = "15%";
//#### calculate the left position of the text:
$dimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textWidth = abs($dimensions[4] - $dimensions[0]);
$leftTextPos = ( $width - $textWidth ) / 2;
//#### finally, write the string:
//imagestring($im, 5, $leftTextPos, $topTextPos, $text, $white);
imagettftext($im, $fontSize, $angle, $leftTextPos + 1, 29, $white, $font, $text);
// output the image
// tell the browser what we're sending it
Header('Content-type: image/png');
// output the image as a png
imagepng($im);
// tidy up
imagedestroy($im);
}
?>
This is producing low quality text (very blocky) - how would one anti alias the text so it looks smooth?
This is the blocky version:
Upon closer analysis of the rendered png (magnified in photoshop) i can see that the text i am writing has no anti aliasing and the pixels being written are almost transparent?
What is causing this - how do i get smooth text?
Explanation:
imagealphablending must be on when using imagettftext on a true-color image, otherwise the aliasing is calculated against the images brackground color instead of the color of each destination pixel.
The correct (explicit) setting would be:
//#### Load the base image
$im = imagecreatefrompng("images/SpecialClearanceBlank.png");
imagealphablending($im, true);
^^^^
Your picture has it enabled by default, that is why setting it to false previously created the non-aliased effect.
Figured it out:
My call to imagealphablending() and imagesavealpha() is what's causing it! If i call these after writing the text it's fine!
(not sure why though - would be interested in an explanation)
Below is the working code to produce this:
<?
Header('Content-type: image/png');
$Percentage = round(#$_GET["value"]);
$root = dirname(__FILE__) . "\\";
//#### Check the Cache
if (file_exists("images/Badges_Discounts/" . $Percentage . ".png") === true) {
//#### Serve image from cache
$im = imagecreatefrompng("images/Badges_Discounts/" . $Percentage . ".png");
//#### Fix transparency
imagealphablending($im, false);
imagesavealpha($im, true);
//#### Output from cache
imagepng($im);
//#### tidy up
imagedestroy($im);
} else {
//#### Load the base image
$im = imagecreatefrompng("images/SpecialClearanceBlank.png");
//#### Create the badge
if($im) {
//#### define some colours to use with the image
$white = imagecolorallocate($im, 255, 255, 255);
//#### get the width and the height of the base image
$width = imagesx($im);
$height = imagesy($im);
//#### Define font and text
$font = $root . "arial.ttf";
$fontSize = 15;
$angle = 0;
$text = $Percentage . "%";
//#### calculate the left position of the text:
$dimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textWidth = abs($dimensions[4] - $dimensions[0]);
$leftTextPos = ( $width - $textWidth ) / 2;
//#### write the XX%
imagettftext($im, $fontSize, $angle, $leftTextPos + 1, 26, $white, $font, $text);
//#### write the word "off"
$dimensions = imagettfbbox($fontSize, $angle, $font, "off!");
$textWidth = abs($dimensions[4] - $dimensions[0]);
$leftTextPos = ( $width - $textWidth ) / 2;
imagettftext($im, 13, $angle, $leftTextPos + 4, 41, $white, $font, "off");
//#### Fix transparency
imagealphablending($im, false);
imagesavealpha($im, true);
//#### Save to cache
imagepng($im, $root . "images\\Badges_Discounts\\" . str_replace("%","",$text) . ".png");
//#### Output to browser
imagepng($im);
//#### tidy up
imagedestroy($im);
}
}
?>

Categories