How to add text on image using PHP - php

I have this image:
Between the text, I want to add some text. To do that I have the following code:
<?php
error_reporting(E_ALL);
$thumb_src = 'copyright-symbol.png';
$explode = explode('.', $thumb_src);
$extension = strtolower( end ( $explode ) );
$file_name = basename( $thumb_src );
//image_resize_base_width( $relative_url, $relative_url, 350, $extension);
$jpg_image = imagecreatefrompng( $thumb_src );
// set font size
$font = #imageloadfont($jpg_image);
$fontSize = imagefontwidth($font);
$orig_width = imagesx($jpg_image);
$orig_height = imagesy($jpg_image);
// Create your canvas containing both image and text
$canvas = imagecreatetruecolor( $orig_width, ($orig_height + 40 ) );
// Allocate A Color For The background
$bcolor = imagecolorallocate( $canvas, 255, 255, 255 );
// Add background colour into the canvas
imagefilledrectangle( $canvas, 0, 0, $orig_width, ($orig_height + 40), $bcolor );
// Save image to the new canvas
imagecopyresampled( $canvas, $jpg_image, 0, 0, 0, 0, $orig_width, $orig_height, $orig_width, $orig_height );
$font_path = 'font/arial.ttf';
$path = 'upload';
$text = 'cc-by-nd-';
// Allocate A Color For The Text
$color = imagecolorallocate($canvas, 0, 0, 0);
// Print Text On Image
imagettftext( $canvas, 13, 0, 0, $orig_height + 25, $color, $font_path, $text) ;
// Send Image to Browser
imagepng( $canvas, $path . '/' . $file_name );
// Clear Memory
imagedestroy($canvas);
But the code is not adding text to the image. Is there anything wrong in my code?

You may change the codes to
<?php
error_reporting(E_ALL);
header('Content-Type: image/png');
$thumb_src = 'copyright-symbol.png';
$explode = explode('.', $thumb_src);
$extension = strtolower( end ( $explode ) );
$file_name = basename( $thumb_src );
//image_resize_base_width( $relative_url, $relative_url, 350, $extension);
$jpg_image = imagecreatefrompng( $thumb_src );
// set font size
$font = #imageloadfont($jpg_image);
$fontSize = imagefontwidth($font);
$orig_width = imagesx($jpg_image);
$orig_height = imagesy($jpg_image);
// Create your canvas containing both image and text
$canvas = imagecreatetruecolor( $orig_width, ($orig_height + 40 ) );
// Allocate A Color For The background
$bcolor = imagecolorallocate( $canvas, 255, 255, 255 );
// Add background colour into the canvas
imagefilledrectangle( $canvas, 0, 0, $orig_width, ($orig_height + 40), $bcolor );
// Save image to the new canvas
imagecopyresampled( $canvas, $jpg_image, 0, 0, 0, 0, $orig_width, $orig_height, $orig_width, $orig_height );
$font_path = './font/arial.ttf';
//$path = 'upload';
// Create some colors
$white = imagecolorallocate($canvas, 255, 255, 255);
$grey = imagecolorallocate($canvas, 128, 128, 128);
$black = imagecolorallocate($canvas, 0, 0, 0);
imagefilledrectangle($canvas, 0, 0, 399, 29, $white);
// The text to draw
// Replace path by your own font path
$font = 'font/arial.ttf';
$text = 'cc-by-nd-';
// Add some shadow to the text
imagettftext( $canvas, 100, 0, ($orig_width / 2) - 300, ($orig_height/2) , $color, $font_path, $text) ;
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($canvas);
imagedestroy($canvas);
?>

Related

Joining 2 images by using PHP GD & Image Functions

I am creating a plugin where i am using a font file to generate the text, then converting it to image and attaching 2 chains on both side to give it a proper look.
But problem is the chains on both side are given by position, so that's obviously not going to touch the text for each and every alphabet.
Any different solutions to make it as intended. I am posting the current code, please let me know how to fix this and attch the chains to the starting and ending alphabet.
$text = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
$color = isset( $_POST['color'] ) ? sanitize_text_field( wp_unslash( $_POST['color'] ) ) : '';
$st yle = isset( $_POST['style'] ) ? sanitize_text_field( wp_unslash( $_POST['style'] ) ) : '';
$align = isset( $_POST['align'] ) ? sanitize_text_field( wp_unslash( $_POST['align'] ) ) : '';
ob_start();
// Set the content-type
header('Content-Type: image/png');
$file_id = get_field( "style", $style );
$font = get_attached_file( $file_id['id'] );
// Create the image
$im = imagecreatetruecolor(400, 400);
$color_code = imagecolorallocate($im, 192, 192, 192);
// Create some colors
$grey = imagecolorallocate($im, 128, 128, 128);
$white = imagecolorallocate($im, 255, 255, 255);
imagealphablending($im, false);
$transparency = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $transparency);
imagesavealpha($im, true);
list($width, $height) = getimagesize($chain_link_l);
$chain_l = imagecreatefrompng($chain_link_l);
$chain_r = imagecreatefrompng($chain_link_r);
$font_size = kp_create_fontsize(60, $font, $text, $align);
// Get Bounding Box Size
$text_box = imagettfbbox($font_size, 0,$font,$text);
// Get your Text Width and Height
$text_width = $text_box[2]-$text_box[0];
$text_height = $text_box[7]-$text_box[1];
// Calculate coordinates of the text
$x = 200 - ($text_width/2);
$y = 250 - ($text_height/2);
$chain_l_x = $x - 80 + 15 ;
$chain_r_x = $x + $text_width - 23 ;
imagecopyresampled($im, $chain_l, $chain_l_x, 50, 0, 0, 100, 200, $width, $height);
imagecopyresampled($im, $chain_r, $chain_r_x, 50, 0, 0, 100, 200, $width, $height);
// Add the text
imagettftext($im, $font_size, 0, $x+2, $y, $grey, $font, $text);
imagettftext($im, $font_size, 0, $x, $y, $color_code, $font, $text);
imagepng($im);
$imagedata['src'] = base64_encode ( ob_get_contents() );
ob_get_clean();

The image is not shown when merging two images in PHP GD library in wordpress

I got this code to work but after few weeks the code is not working ,i did try to see where the bug come from but i have no idea.
I did create image with GD library and it is created successfully but when i want to merge it with another picture it show only black screen.Any idea of how to solve the issue please .Here is my code:
Please note that the image is created and saved successfully,so there is no problem with create_image() function.
function create_image()
{
$cer_id = get_the_ID();
$cer_org_nummer = get_field('orgnummer_dqm');
$cer_today = date('Y-m-d');
$cer_org_name = get_field('foretags_namn_dqm');
$cer_org_date = $cer_org_nummer . ' | ' . $cer_today;
$im = #imagecreate(500, 450);
$yellow = imagecolorallocate($im, 255, 255, 255); // yellow
imagecolortransparent($im, $yellow);
$black = imagecolorallocate($im, 252, 195, 91);
$string = "Digital Quality Managment";
$font = FUNC_PLUGIN_D_DQM . '/font/Roboto-Regular.ttf';// black
/* imagestring($im, $font, 50, 300, $string, $black);*/
/* imagestring($im, $font, 3, 300, $cer_org_name, $black);*/
/* imagestring($im, $font, 0, 10, $cer_org_date, $black);*/
imagettftext($im, 35, 0, 60, 270, $black, $font, 'CERTIFIED');
imagettftext($im, 25, 0, 0, 320, $black, $font, $cer_org_date);
imagepng($im, "wp-content/plugins/certificates/cer_images/image_$cer_id.png");
imagedestroy($im);
}
create_image();
$image1 = "wp-content/plugins/certificates/cer_images/dqm_png_logo.png";
$image2 = "wp-content/plugins/certificates/cer_images/image_$cer_id.png";
list($width, $height) = getimagesize($image2);
$image1 = imagecreatefromstring(file_get_contents($image1));
$image2 = imagecreatefromstring(file_get_contents($image2));
imagealphablending($image1, FALSE);
imagesavealpha($image1, TRUE);
imagecopymerge($image1, $image2, 110, 50, 0, 0, $width, $height, 100);
header("Content-type: image/png");
imagepng($image1);
imagedestroy($image1);
please try the code below
This code works for me..
$pro_directory_path = get_attached_file( get_post_thumbnail_id($_REQUEST['apid']),'full' );
$mainmetadata = wp_get_attachment_metadata( get_post_thumbnail_id( $_REQUEST['apid'] ) );
$pro_img_name = $mainmetadata['file'];
$pro_img_name_extra = '1'.$mainmetadata['file'];
// $val_id is id of image(bigger image/background Image)
$directory_path = get_attached_file( $val_id,'full' );
$metadata = wp_get_attachment_metadata( $val_id );
$name = $metadata['file'];
$bgFile = $directory_path;
// We want our final image to be 76x76 size
//user $metadata to get ordiginal height width of image
// $value contain height width of wall mentioned by admin
$x = $metadata['width'];
$y = $metadata['height'];
$x_inch = $metadata['width']/96;
$y_inch = $metadata['height']/96;
$width_proption = $wall_w_inch/$x_inch;
$height_proption = $wall_h_inch/$y_inch;
$img_pos_x = ($x/2)-($resizedwidth/2);
$img_pos_y = ($y/2)-($resizedheight);
/* Code to generate custom wall images - STart */
$inn_width = ($innerimg_width / $width_proption) * 12 ;
$inn_height = ($innerimg_height / $height_proption) * 12 ;
$resizedFilename = get_template_directory().'/woocommerce/temp_images/cust_'.$pro_img_name;
$img_url_extra = get_stylesheet_directory_uri().'/woocommerce/temp_images/cust_'.$pro_img_name;
//function to resize Artist product image in desired size's (Variation sizes).
$imgData = resize_image($pro_directory_path, $inn_width, $inn_height);
imagepng($imgData, $resizedFilename);
list($resizedwidth, $resizedheight) = getimagesize($resizedFilename);
/* Code to generate custom wall images - ENDS */
$imageFile = $resizedFilename;
// dimensions of the final image
$final_img = imagecreatetruecolor($x, $y);
// Create our image resources from the files
$image_1 = imagecreatefrompng($bgFile);
$image_2 = imagecreatefrompng($imageFile);
// Enable blend mode and save full alpha channel
imagealphablending($final_img, true);
imagesavealpha($final_img, true);
// Copy our image onto our $final_img
imagecopy($final_img, $image_1, 0, 0, 0, 0, $x, $y);
imagecopy($final_img, $image_2, $img_pos_x, $img_pos_y, 0, 0, $resizedwidth, $resizedheight);
ob_start();
$path = __DIR__ .'/custom_wall_img/'.$name;
imagepng($final_img,$path);
$watermarkedImg = ob_get_contents(); // Capture the output
ob_end_clean(); // Clear the output buffer

how to put some text on image on particular area in php using GD

i want to generate online certificates using GD in php, certificate image format is ready with me. just i want to put candidate name and other details on image as a text in particular area. i have image file in jpg, gif and png format
Here is a Complete Example with text and certificate image
<?php
function LoadGif($imgname)
{
/* Attempt to open */
$im = #imagecreatefromgif($imgname);
// Allocate A Color For The Text
$black = imagecolorallocate($im, 0, 0, 0);
// Set Path to Font File
$font_path = 'ARIALNB.TTF';
// Set Text to Be Printed On Image
$candidate_name = "Chirag jagani";
$speed = "8829";
$percentage = "98%";
$mintues ="4:00";
$date="The 1st Day of July in the Year 2015";
// Print Text On Image
//imagettftext(image, size, varitcal means 90, X cordinates, Y coordinates, $white, $font_path, $speed);
//candidate name
imagettftext($im, 54, 90, 199, 713, $black, $font_path, $candidate_name);
//speed
imagettftext($im, 13, 90, 271, 620, $black, $font_path, $speed);
//percentage
imagettftext($im, 14, 90, 310, 605, $black, $font_path, $percentage);
//mintues
imagettftext($im, 13, 90, 331, 350, $black, $font_path, $mintues);
//date
imagettftext($im, 22, 90, 382, 610, $black, $font_path, $date);
/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor (150, 30);
$bgc = imagecolorallocate ($im, 255, 255, 255);
$tc = imagecolorallocate ($im, 0, 0, 0);
imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/gif');
$img = LoadGif('main.gif');
imagegif($img);
imagedestroy($img);
?>
let me know if you have any query.
all the best :)
How to create a watermark on an existing image..
//-------------------------------------------------------------------------
$wWidth = 280; // set watermark image width
$wHeight = 50; // set watermark image height
// Create the watermark image
$watermark = imagecreate( $wWidth, $wHeight );
$black = imagecolorallocate( $watermark, 0, 0, 0 ); // define a colour to use
$white = imagecolorallocate( $watermark, 255, 255, 255 ); // define a colour to use
// Create a rectangle and fill it white
imagefilledrectangle( $watermark, 0, 0, $wWidth, $wHeight, $white );
// Make white transparent
#imagecolortransparent ( $watermark, $white );
$font = 'fonts/arial.ttf'; // store path to the font file
$wText = "(c) Chris Maggs ".date('Y'); // set watermark text
$wSize = "20"; // set the watermark font size
// Calculate the size of $wText (requires php/gd with ttf support)
$box = imagettfbbox( $wSize, 0, $font, $wText );
$x = ( $wWidth - ($box[2] - $box[0]) ) / 2;
$y = ( $wHeight - ($box[1] - $box[7]) ) / 2;
$y -= $box[7];
// Add $wText to the image
imagettftext( $watermark, $wSize, 0, $x, $y, $black, $font, $wText );
// Save the text image as temp.png
imagepng( $watermark, "uploads/temp.png" );
// Cleanup the image memory usage
imagedestroy( $watermark );
//-------------------------------------------------------------------------
// Set the path to the image to watermark
$input_image = "resources/tenby.jpg";
// Read in the text watermark image
$watermarkImage = imagecreatefrompng( "uploads/temp.png" );
$watermark_width = imagesx( $watermarkImage ); // width of image resource
$watermark_height = imagesy( $watermarkImage ); // height of image resource
// Create a new image resource
$image = imagecreatefromjpeg( $input_image );
// Find the size of the original image and read it into an array
$size = getimagesize( $input_image );
// Set the positions of the watermark on the image
$dest_x = $size[0] - $watermark_width;
$dest_y = $size[1] - $watermark_height;
// Merge 2 image resources..
imagecopymerge($image, $watermarkImage, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 50);
// OPTION 1 : save the watermarked image as watermarked.jpg
imagejpeg( $image, "uploads/watermarked.jpg" );
// OPTION 2 : output the watermarked image
header("Content-type: image/jpeg");
imagejpeg( $image );
// delete the text watermark image
unlink( "uploads/temp.png");
// Cleanup the image memory usage
imagedestroy( $image );

how to create image and header it in PHP?

I have one problem with PHP create image. What is wrong with my following code?
<?php
$filename = 'play';
$img = "http://www.slcentral.com/ipod-mp3-player/5.JPG";
$image = imagecreatefromjpeg($img);
$cleft = 0;
$ctop = 45;
$canvas = imagecreatetruecolor(480, 270);
imagecopy($canvas, $image, 0, 0, $cleft, $ctop, 480, 360);
$image = $canvas;
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
// ADD THE PLAY ICON
$play_icon = "f-play.png";
$logoImage = imagecreatefrompng($play_icon);
imagealphablending($logoImage, TRUE);
$logoWidth = imagesx($logoImage);
$logoHeight = imagesy($logoImage);
// CENTER PLAY ICON
$left = round($imageWidth / 2) - round($logoWidth / 2);
$top = round($imageHeight / 2) - round($logoHeight / 2);
// CONVERT TO PNG SO WE CAN GET THAT PLAY BUTTON ON THERE
imagecopy( $image, $logoImage, $left, $top, 0, 0, $logoWidth, $logoHeight);
imagepng( $image, $filename .".png", 9);
// MASHUP FINAL IMAGE AS A JPEG
$input = imagecreatefrompng($filename .".png");
$output = imagecreatetruecolor($imageWidth, $imageHeight);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $imageWidth, $imageHeight, $white);
imagecopy($output, $input, 0, 0, 0, 0, $imageWidth, $imageHeight);
// OUTPUT TO 'i' FOLDER
header("Content-type: image/jpeg");
imagejpeg($output, $filename . ".jpg", 95);
// UNLINK PNG VERSION
#unlink($filename .".png");
die();
?>
Above code is create one image from giving url and add play icon to it. And I want to access to http://coolrss.com/create-img.php it will show image with play icon.
Please help!
Make sure the path has the right permission or you will get:
PHP Warning: imagepng(): Unable to open 'play.png' for writing: Permission denied in /var/www/coolrss/public_html/create-img.php on line 32
Make sure you have installed GD.
Start your code with this header (after the php tag (<?php))
header("Content-Type: image/jpeg");
At the end (last line) add
imagejpeg($output, NULL, 100);
Your code looks like this now:
<?php
header("Content-Type: image/jpeg");
$filename = 'play';
$img = "http://www.slcentral.com/ipod-mp3-player/5.JPG";
$image = imagecreatefromjpeg($img);
$cleft = 0;
$ctop = 45;
$canvas = imagecreatetruecolor(480, 270);
imagecopy($canvas, $image, 0, 0, $cleft, $ctop, 480, 360);
$image = $canvas;
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
// ADD THE PLAY ICON
$play_icon = "f-play.png";
$logoImage = imagecreatefrompng($play_icon);
imagealphablending($logoImage, TRUE);
$logoWidth = imagesx($logoImage);
$logoHeight = imagesy($logoImage);
// CENTER PLAY ICON
$left = round($imageWidth / 2) - round($logoWidth / 2);
$top = round($imageHeight / 2) - round($logoHeight / 2);
// CONVERT TO PNG SO WE CAN GET THAT PLAY BUTTON ON THERE
imagecopy( $image, $logoImage, $left, $top, 0, 0, $logoWidth, $logoHeight);
imagepng( $image, $filename .".png", 9);
// MASHUP FINAL IMAGE AS A JPEG
$input = imagecreatefrompng($filename .".png");
$output = imagecreatetruecolor($imageWidth, $imageHeight);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $imageWidth, $imageHeight, $white);
imagecopy($output, $input, 0, 0, 0, 0, $imageWidth, $imageHeight);
imagejpeg($output, NULL, 100);
Screenshot - Works for me

PHP watermark cannot upload png

my script it work with jpg , jpeg , bmp when i upload and succsess.
but when i upload png , gif it stored in my folder but the image is blank with black background color.
is there any way to solve this?
$water_mark_text_2 = "text";
$font_path = "fonts/BRLNSR.TTF";
$font_size = 25; // in pixcels
//$water_mark_text_1 = "9";
function watermark_text($oldimage_name, $new_image_name){
global $font_path, $font_size, $water_mark_text_1, $water_mark_text_2;
list($width,$height) = getimagesize($oldimage_name);
$image = imagecreate(100, 100);
// sets some colors
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$image = imagecreatetruecolor($width, $height);
$image_src = imagecreatefromjpeg($oldimage_name);
imagecopyresampled($image, $image_src, 0, 0, 0, 0, $width, $height, $width, $height);
//imagecopyresampled($image, $stamp, $image_src, 0, 0, 0, 0, $width, $height, $width, $height , imagesx($stamp), imagesy($stamp), 60);
// $black = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 79, 166, 185);
// imagettftext($image, $font_size, 0, 30, 190, $black, $font_path, $water_mark_text_1);
imagettftext($image, $font_size, 0, 5, 20, $white, $font_path, $water_mark_text_2);
imagejpeg($image, $new_image_name, 100);
imagedestroy($image);
unlink($oldimage_name);
return true;
}
$path = "$stored/";
$valid_formats = array("jpg", "bmp","jpeg","JPG","png");
$name = $_FILES['img']['name'];
list($txt, $ext) = explode(".", $name);
$upload_status = move_uploaded_file($_FILES['img']['tmp_name'],$path.$name);
$new_name = $stored.$md5_img.".jpg";
watermark_text($path.$_FILES['img']['name'], $new_name);
if i change imagecreatefromjpeg to imagecreatefrompng , and imagejpg to imagepng.
the image still upload , but i cannot opened.

Categories