How add image created in GD to template - php

I am looking for help with one problem. I would like to create an image using imageJpeg. And this image add to template using openTBS.
template:
[b.image;ope=changepic;from=[val];default=current;adjust]
php:
$TBS = $this->get('opentbs');
$TBS->NoErr = TRUE;
$TBS->LoadTemplate('template.odt', OPENTBS_ALREADY_UTF8);
$image = imageCreate(300,200);
$colorRed = imageColorAllocate($image, 255,0,0);
$colorYellow = imageColorAllocate($image, 255,255,0);
imageFilledRectangle($image, 50, 50, 250, 150, $colorYellow);
$cccc=imageJpeg($image);
imageDestroy($image);
$data = array('image'=>$cccc);
$TBS->MergeField('b', $data);
$TBS->Show(OPENTBS_DOWNLOAD, 'file_name.odt');
However, image does not fit in the template sizes. After opening the file, only generated image is visible.

According to the documentation, imageJpeg() creates the image and return a boolean.
So a nice solution is to use a temporary file :
...
$tmp = tempnam(sys_get_temp_dir(), 'tbs');
$cccc=imageJpeg($image, $tmp);
imageDestroy($image);
$data = array('image'=>$tmp);
$TBS->MergeField('b', $data);
$TBS->Show(OPENTBS_DOWNLOAD, 'file_name.odt');

Related

PHP: embed text in image when uploading it

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.

Running imagecreatefrompng throught image array but array just returns 1 image

I'm trying to crop of the bottom part of an image, which i get from a remote site.
Got it also working with the following code:
$u = $xmlString->xpath('//*[contains(#u, "/fds/")]');
foreach($u as $result) {
$itemLinks = 'http://exampleurl/'.$result['u'].'.png';
$in_filename = $itemLinks;
list($width, $height) = getimagesize($in_filename);
$offset_x = 0;
$offset_y = 0;
$new_height = $height - 264;
$new_width = $width;
$image = imagecreatefrompng($in_filename);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$transparentindex = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
imagefill($new_image, 0, 0, $transparentindex);
imagecopy($new_image, $image, 0, 0, $offset_x, $offset_y, $width, $height);
header("Content-Type: image/png");
imagepng($new_image);
}
The only problem with this code is the following:
I'm getting the Image Path from a remote XML file, which i filtered with xpath. So all my finished Image url's are stored in an array. But my code is just generating 1 image which contains the perfect size which i need.
It happens because its just generating 1 img in the end. Maybe also happens because it just returns 1 image with the name img.
Question: Does anyone have a idea why it wouldnt return all images?
For example:
Array contains 15 image links.
Im running my foreach loop through the array.
Foreach loop returns only 1 image.
Your issue is caused by the last two lines:
header("Content-Type: image/png");
imagepng($new_image);
This has the same effect as opening a single image file (like a .PNG) in your browser. You can't view multiple image files at the same time unless they are embedded in a HTML page.
If you want to show all fifteen images at once in the browser you'll need to save each image as you process it and then output an HTML file, something like this:
$images = '';
foreach($u as $result) {
// your existing code...
imagepng($new_image, './'.$result['u'].'.png');
$images .= '<img src="'.$result['u'].'.png">';
}
// wrap this in valid HTML syntax (<head>, <body>, etc.)
echo $images;

php gd function to draw polyline from array

may be you can help me.
I need a function to draw polyline path from _GET or _POST string and save generated image to the folder.
For example my link will looks like: http://img.domain.com/?points = 1,5,-70,300,250,500...
If image already generated and do not changed -> load it from folder. Else generate new one.
My code here:
if (isset($_POST['points'])) {
$points = $_POST['points'];
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
... polyline path drawing here...?
imageline($image, 10, 10, 10, 190, $black);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
... how to save it to the server?
}
Thanks.
To save the image you can use the second (optional) parameter of imagepng:
imagepng($image, 'saved.png');
For the polyline you will be calling imageline inside a loop -- exactly how depends on what your $points value is structured.
To save an image to the server on the fly, use the image function's second parameter to specify a location and filename.
//specify the path on the server where you want to save the image
$path_image = 'saved-example.png';
imagepng($image, $path_image);
imagepng($image);
imagedestroy($image);
Image will be saved to that path.

PHP imagecopy with transparent background

I use this code to create an image from another png image, the background is black by default. My question is how to set a transparent background?
$input = imagecreatefrompng('image.png');
$output = imagecreatetruecolor(50, 50);
imagecopy($output, $input, 4,0, 8,8, 8,8);
imagecopy... etc.
header('Content-Type: image/png');
imagepng($output);
Is there a easy way of doing this? Thanks
Sets the transparent color in the given image.
int imagecolortransparent ( resource $image [, int $color ] )
Here's the link
Since the PHP function imagecopymerge doesn't work with the Alpha channel, you'll want to use the function from the first comment on this page imagecopymerge_alpha:
http://php.net/manual/en/function.imagecopymerge.php
Just have the transparent image as the base and merge it together with the image you need.
I've tried it out and it works fine for a project of mine.
None of the solutions worked for me, it would always convert transparent pixels on the source image to black on the destination image. What worked was changing imagecopy/imagecopymerge/imagecopymerge_alpha to imagecopyresampled and just passing the same width and height twice.
//Create destination image.
$png = imagecreatetruecolor(1024, 1024);
imagealphablending($png, false);
imagesavealpha($png, true);
//Make destination image be all transparent.
$color = imagecolorallocatealpha($png, 0, 0, 0, 127); //127 means completely transparent.
imagefill($png, 0, 0, $color);
//Load source image.
$png2 = imagecreatefrompng($sourceurl);
imagealphablending($png2, false);
imagesavealpha($png2, true);
$sizex = imagesx($png2);
$sizey = imagesy($png2);
//Copy to destination and save to file.
imagecopyresampled( $png, $png2,
0, 0,
0, 0,
$sizex, $sizey,
$sizex, $sizey);
imagepng($png, "result.png");
imagealphablending($input, true);
imagesavealpha($input, true);
imagealphablending($output, true);
imagesavealpha($output, true);
Or propably
int imagesavealpha($img,true);
http://www.php.net/manual/en/function.imagesavealpha.php
Full credit goes to:
http://consistentcoder.com/combine-a-transparent-png-image-on-top-of-another-image-with-php
The following code will overlay the foreground image onto the background image while preserving the transparency of the overlay:
//set the source image (foreground)
$sourceImage = 'table.png';
//set the destination image (background)
$destImage = 'create-a-surreal-head-of-tree-photo-manipulation.jpg';
//get the size of the source image, needed for imagecopy()
list($srcWidth, $srcHeight) = getimagesize($sourceImage);
//create a new image from the source image
$src = imagecreatefrompng($sourceImage);
//create a new image from the destination image
$dest = imagecreatefromjpeg($destImage);
//set the x and y positions of the source image on top of the destination image
$src_xPosition = 75; //75 pixels from the left
$src_yPosition = 50; //50 pixels from the top
//set the x and y positions of the source image to be copied to the destination image
$src_cropXposition = 0; //do not crop at the side
$src_cropYposition = 0; //do not crop on the top
//merge the source and destination images
imagecopy($dest,$src,$src_xPosition,$src_yPosition,
$src_cropXposition,$src_cropYposition,
$srcWidth,$srcHeight);
//output the merged images to a file
/*
* '100' is an optional parameter,
* it represents the quality of the image to be created,
* if not set, the default is about '75'
*/
imagejpeg($dest,
'combine-a-transparent-png-image-on-top-of-another-image-with-php-01.jpg',
100);
//destroy the source image
imagedestroy($src);
//destroy the destination image
imagedestroy($dest);

Generating preview images for DOC, TXT and RTF files

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.

Categories