So I have this php script which generates random text on an image.
The text file is a different php file and the image file is a seperate php file.
The image.php file calls this text.php to select a random text.
This version works fine, but is it possible to generate a random image on my existing image file?
I have included the current versions of my code.
This is text.php:
<?php
$t[] = 'Sample text 1 ';
$t[] = 'Sample text 2';
shuffle($t);
?>
This is image.php:
<?php
require_once 'text.php';
$text = wordwrap($t[0], 31, "\n", true); //text
$image = imagecreatefromjpeg('img_empty.jpg'); //background image
?>
Any suggestions are welcome.
Your question is bit unclear.. You don't want text.php then you can directly use it's code in image.php as shown below.
image.php
<?php
$t[] = 'Sample text 1 ';
$t[] = 'Sample text 2';
shuffle($t);
$text = wordwrap($t[0], 31, "\n", true); //text
$image = imagecreatefromjpeg('img_empty.jpg'); //background image
Several options here
Have several background-images saved and select one randomly among them.
Use GD and Image Functions to draw on your existing image before outputting it (look at imageline() for drawing lines for example).
Use GD's imagecreatetruecolor() to create the image, to even get random width/height.
if you want to create an image with random text this will do it
image.php
require_once 'text.php';
header("Content-type: image/png");
$string = wordwrap($t[0], 31, "\n", true); //text
$font = 2;
$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);
UPDATED CODE TO YOUR RESPONSE:
if you want to get your random text over a specific image
require_once 'text.php';
header("Content-type: image/png");
$string = wordwrap($t[0], 31, "\n", true); //text
$image = ImageCreateFromJPEG("img_empty.jpg");
//Defining color. Making the color of text as red (#FFF) as 255,000,000
$color = imagecolorallocate($image , 255, 000, 000); //
//put string over image with $color as color
imagestring($image,5,126,22,$string,$color);
imagejpeg($image,NULL,100);
The above code will put a red color random text over your specified image.this works for me. Also try changing the colors defined in imagecolorallocate() function.
reference: http://blog.doh.ms/2008/02/12/adding-text-to-images-in-real-time-with-php/
Related
I followed this example to embed text in image while uploading it but it's not working.
This is my code:
header('Content-type: image/jpeg');
$img = $_FILES['mainImage']['name'];
list($txt, $ext) = explode(".", $img);
$imgName = "ac_".time().".".$ext;
$tmp = $_FILES['mainImage']['tmp_name'];
$textToImage = imagecreatefromjpeg($tmp);
// Allocate A Color For The Text
$white = imagecolorallocate($textToImage, 255, 255, 255);
// Set Path to Font File
$font_path = '../assets/fonts/font.ttf';
// Set Text to Be Printed On Image
$text = "Test text";
// Print Text On Image
imagettftext($textToImage, 25, 0, 75, 300, $white, $font_path, $text);
$imageUploaded = move_uploaded_file($tmp, 'images_path/'.$imgName);
if(!$imageUploaded){
die('Error upload image!');
}
The image is uploaded but wihout text in it !
For this we are working with GD library.
"PHP is not limited to creating just HTML output. It can also be used
to create and manipulate image files in a variety of different image
formats, including GIF, PNG, JPEG, WBMP, and XPM. Even more
convenient, PHP can output image streams directly to a browser. You
will need to compile PHP with the GD library of image functions for
this to work. GD and PHP may also require other libraries, depending
on which image formats you want to work with."
You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.
The following code sample demonstrates the use of GD library to watermark images on the fly. The method demonstrated here to watermark an uploaded image is to overlay the original image with another image, preferably a transparent PNG image.
PHP provides a rich set of functions to create and alter images on the fly. These functions require the GD library, which is bundled with PHP since version 4.3.
The HTML form needs a file upload element: <input type="file">. You must also specify the correct encoding type: enctype="multipart/form-data" for the form.
/ link to the font file no the server
$fontname = 'font/Capriola-Regular.ttf';
// controls the spacing between text
$i=30;
//JPG image quality 0-100
$quality = 85;
function create_image($user){
global $fontname;
global $quality;
$file = "covers/".md5($user[0]['name'].$user[1]['name'].$user[2]['name']).".jpg";
// if the file already exists dont create it again just serve up the original
if (!file_exists($file)) {
// define the base image that we lay our text on
$im = imagecreatefromjpeg("pass.jpg");
// setup the text colours
$color['grey'] = imagecolorallocate($im, 54, 56, 60);
$color['green'] = imagecolorallocate($im, 55, 189, 102);
// this defines the starting height for the text block
$y = imagesy($im) - $height - 365;
// loop through the array and write the text
foreach ($user as $value){
// center the text in our image - returns the x value
$x = center_text($value['name'], $value['font-size']);
imagettftext($im, $value['font-size'], 0, $x, $y+$i, $color[$value['color']], $fontname,$value['name']);
// add 32px to the line height for the next text block
$i = $i+32;
}
// create the image
imagejpeg($im, $file, $quality);
}
return $file;
}
function center_text($string, $font_size){
global $fontname;
$image_width = 800;
$dimensions = imagettfbbox($font_size, 0, $fontname, $string);
return ceil(($image_width - $dimensions[4]) / 2);
}
$user = array(
array(
'name'=> 'Slimen Tunis',
'font-size'=>'25',
'color'=>'black'),
array(
'name'=> 'Web developer',
'font-size'=>'16',
'color'=>'grey'),
array(
'name'=> 'SlimenTunis#webdeveloper.com',
'font-size'=>'13',
'color'=>'green'
)
);
// run the script to create the image
$filename = create_image($user);
here we have two functions to make it as simple as possible. To run the code simply pass the $user array data to the function and it’ll save the new image in the folder ‘covers’ on your server. The function returns the file url so you just need to echo it into an image tag as shown below. Check out the demo where you can create your own.
$filename = create_image($user);
<img src="<?=$filename;?>" width="800" height="600"/>
You can try using the Intervention library. I use it for doing what you're asking about. It is quite simple to understand and the documentation is is well-written.
I am trying to combine two pieces of code in one. The first part convert the given .jpg image to .png and put it to IMG folder with the same name just different extension.
The second part of the code should print "text" over the picture while taking the picture from the folder IMG (the .png image created by the FIRST PART).
I am doing something wrong obviously as what I get printed in the end is just the source of the picture instead of using the < img src= part in the end.
I have tried to search for some identical issues here, but with no luck.
//FIRST PART
$file = basename($picture, ".jpg");
$file_create = "img/$file.png";
$image = ImageCreateFromJPEG("$picture");
ImageJpeg($image, "img/$file.png");
ImageDestroy($image);
//SECOND PART
header("Content-type: image/png");
$imgPath = "$file_create";
$image = imagecreatefromjpeg($imgPath);
$color = imagecolorallocate($image, 255, 255, 255);
$string = "test";
$fontSize = 3;
$x = 115;
$y = 185;
imagestring($image, $fontSize, $x, $y, $string, $color);
$final=imagejpeg($image);
print "<img src='img/$final' width=150 height=150 valign=middle title='$item' alt='$item'>";
Any ideas?
Here is a good tutorial for same
http://www.phpforkids.com/php/php-gd-library-adding-text-writing.php
Good day everyone.
Long story short, I'm trying to make an online card game much like urban rivals.
To do so, I'm using mainly PHP and SQL.
Right now, I'm trying to generate the png file of a card based on a database.
I've already managed to merge images with alpha channel, to add text to an image, but my real problem is : I cannot seem to be able to output this image along with other and the basic layout of a HTML document. Here is my test code :
<?php
include 'phpGDtools.php';
$image1path = 'monstercard.png';
$image2path = 'monsterimage.png';
$xdim = 220;
$ydim = 301;
//$image = mergeTwoPNGAndReturn($image1path, $image2path, $xdim, $ydim);
mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim);
echo('Hello !');
?>
Sorry for the bad formatting, I haven't been able to make it better :/
Here is my function in phpGDTools.php:
function mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim)
{
//TEST FUNCTION
//Both paths to the images, x and y dimensions of the image you're about to fuse.
$final_img = imagecreate($xdim, $ydim);
//Step 1 : Create the objects from the PNGs
$image_1 = imagecreatefrompng($image1path);
$image_2 = imagecreatefrompng($image2path);
//Step 1.2 : Allow transparency of bases.
imagealphablending($image_1, true);
imagesavealpha($image_1, true);
imagealphablending($image_2, true);
imagesavealpha($image_2, true);
//Step 2 : Merge the images into one.
imagecopy($image_1, $image_2, 0, 0, 0, 0, $xdim, $ydim);
imagecopy($final_img, $image_1, 0, 0, 0, 0, $xdim, $ydim);
//Step 3 : Allow transparency of final image.
imagealphablending($final_img, true);
imagesavealpha($final_img, true);
//Step 4 : Output image to browser.
header('Content-Type: image/png;');
imagepng($image_1);
}
This outputs very well the image, as intended, but the text "Hello !" is nowhere to be found.
Also, please ignore the part about "$final_image" it's just for testing.
You may have noticed I commented this line :
//$image = mergeTwoPNGAndReturn($image1path, $image2path, $xdim, $ydim);
This is the function I want to use : hopefully, my goal would be to include this php file into an html page, and then being able to print the image object between two tags.
Technically, I could save it as afile and then output the file, but that would be extremely inefficient considering my project.
Thank you for helping me out.
~Jules Courtois
You're setting the content type to an image, so anything you send back will be interpreted as an image. When you're echoing HTML you're adding to the image data which is resulting in the browser not being able to read the image.
You need to create a HTML page then reference images within the HTML file with a or tag with the src to the URL of the image or you can base64 an image to use it inline.
You could replace
imagepng($image_1);
with
ob_start();
imagejpeg($image_1);
$image_data = ob_get_contents ();
ob_end_clean ();
$image_data_base64 = base64_encode($image_data);
echo '<img src="data:image/png;base64,' . $image_data_base64 . '" />';
You should avoid processing images on the fly and try to store them but this should achieve what you asked in the question.
It looks like you are trying to output image data and html data from the same php script.
You call the function
mergeTwoPNGAndOutputInBrowser();
which outputs the image header to the browser.
And then you
echo('Hello !');
Where 'hello' is text data and not image data... So its not displayed in the image.
You could do something like this.
<?php
include 'phpGDtools.php';
$image1path = 'monstercard.png';
$image2path = 'monsterimage.png';
$xdim = 220;
$ydim = 301;
if(isset($_GET['display_image'])){
//Output image data
mergeTwoPNGAndOutputInBrowser($image1path, $image2path, $xdim, $ydim);
}
else{
//Output page data
echo 'Hello !';
echo "<img src=\"?display_image\">";
}
?>
The Text is not displaying since you have set the header
header('Content-Type: image/png;');
Why don't you use the imagestring() of the same PHP GD Library. It let's you write text on the image.
Here's a cool example. You can embed this same code to your mergeTwoPNGAndOutputInBrowser() function.
<?php
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Source
been messing with imagestring trying to change font & font size but i really dont have a clue, i'm new to php and have worked on some code that i came across on a forum and have made it work for me just need to find a way to change font and font size but everything i've tried hasn't given me a good outcome.. any solutions? Please bare in mind i'm new to php and if you could explain as much as possible for your answer thank you so much
$im = imagecreatefrompng("image.png");
// if there's an error, stop processing the page:
if(!$im)
{
die("");
}
// define some colours to use with the image
$black = imagecolorallocate($im, 80, 77, 77);
$font = 'cour.ttf';
// get the width and the height of the image
$width = imagesx($im);
$height = imagesy($im);
$textt = $_GET['textt'];
$dealer = $_GET['dealer'];
$purchase = $_GET['purchase'];
$name = $_GET['name'];
$address = $_GET['address'];
$address1 = $_GET['address1'];
// store the text we're going to write in $textt
putenv('GDFONTPATH=' . realpath('cour.ttf'));
// calculate the left position of the text:
$leftTextPos = ( $width - imagefontwidth($font)*strlen($textt) )/2;
$leftTextPos = ( $width - imagefontwidth($font)*strlen($dealer) )/2;
// finally, write the string:
imagestring($im,$font,$leftTextPos-210,$height-295,$textt,$black);
imagestring($im,$font,$leftTextPos-210,$height-165,$dealer,$black);
imagestring($im,$font,$leftTextPos-200,$height-115,$purchase,$black);
imagestring($im,$font,$leftTextPos-130,$height-70,$name,$black);
imagestring($im,$font,$leftTextPos-100,$height-50,$address,$black);
imagestring($im,$font,$leftTextPos-00,$height-50,$address1,$black);
// 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);
?>
You should try to use imagettftext function.
I've been trying to find a method of achieving this for awhile now with no luck.
Unfortunately none of these formats are supported by ImageMagicK
Thanks
Customize the code to fit into your requirements.
I've attached a sample image generated from a text file that contains "Generating preview images for TXT files" sentence by the following code:
<?php
Header ("Content-type: image/gif");
$txtfile = "test.txt";
$testarr = array();
if(!file_exists($txtfile)){
$string = "File not found.";
}
else{
$testarr = file($txtfile);
srand ((float) microtime() * 10000000);
$string = '-'.$testarr[array_rand($testarr)];
$string = substr($string,0,strlen($string)-2);
}
$font = 4;
$width = ImageFontWidth($font)* strlen($string);
$height = ImageFontHeight($font);
$im = ImageCreate($width,$height);
$x=imagesx($im)-$width ;
$y=imagesy($im)-$height;
$background_color = imagecolorallocate ($im, 242, 242, 242); // white colored background
$text_color = imagecolorallocate ($im, 0, 0,0); // black colored text
$trans_color = $background_color; // transparent
imagecolortransparent($im, $trans_color);
imagestring ($im, $font, $x, $y, $string, $text_color);
imagegif($im);
ImageDestroy($im);
?>
Links would be useful :
http://visionmasterdesigns.com/tutorial-convert-text-into-transparent-png-image-using-php/
http://www.phpro.org/examples/Text-to-Image-with-GD.html
I think you are going to need to do this on a machine with a GUI/Window environment by opening the files and then taking screenshots of them like http://litmus.com/ or https://browserlab.adobe.com/en-us/index.html
There is a program written do this for PDFs from HTML using WebKits rendering engine: http://code.google.com/p/wkhtmltopdf/
My suggestion is to convert all those documents to pdf and then print that pdf to image.
For Doc to PDF, you could try LiveDocx.