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.
Related
I am able to successfully resize (to the proper resized dimensions) an image that I have created from one page of a pdf document. However, I do not understand why the result is a dark resized image with a patch of white. Please, can someone advise?
PHP code:
// Create image from first page of pdf document
$im = new imagick('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
$imageHeight = $im -> getImageHeight();
$imageWidth = $im -> getImageWidth();
$desiredImgWidth = 200;
$desiredImgHeight = resizedImageHeight($imageWidth, $imageHeight,
$desiredImgWidth);
$im -> resizeImage($desiredImgWidth, $desiredImgHeight,
imagick::STYLE_NORMAL, 1);
// Save image
$page = '1';
$saveToFolder = 'thumbnailFolder';
$fileName = 'thanhThumbNail_'.$page.'.jpg';
$saveImgToPath = $saveToFolder.'/'.$fileName;
$result = file_put_contents($saveImgToPath, $im);
function resizedImageHeight($imgWidth, $imgHeight, $desiredImgWidth){
$quoient = $imgWidth/$imgHeight;
$height = $desiredImgWidth/$quoient;
return $height;
}
Resulting thumbnail image:
Link to original PDF can be found here:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4905263/pdf/ksgt-06-04-1091539.pdf
Your PDF has transparency. JPG does not support transparency and shows black where the PDF was transparent. Just turn the transparency off. In Imagemagick command line:
convert -density 300 ksgt-06-04-1091539.pdf[0] -alpha off result.jpg
See setImageAlphaChannel at http://us3.php.net/manual/en/imagick.setimagealphachannel.php
Looks like the background color is not defined. You need to set the background color before reading the PDF document.
// Create image from first page of pdf document
$im = new imagick();
$im->setBackgroundColor('WHITE');
$im->readImage('1Mpublic.pdf[0]');
$im->setImageFormat('jpg');
I have a PHP function that uses Imagick. I am trying to pull a non-square image from a URL and size it up to 500x500px where it doesn't stretch but fits inside this area. Additionally, I am using the Laravel framework and this function is in a controller that is rendered via route.
function myFunction()
{
function createGrid()
{
$placeholder = "https://placeholdit.imgix.net/~text?txtsize=33&txt=&w=500&h=500";
$im = new imagick("http://www.masters.com/images/pics/large/h_2015041243595.jpg");
$image = $im->resizeImage(500, 500, 0, 0, true);
// $target = new Imagick($placeholder);
// $target->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
// $target->compositeImage($image, imagick::COMPOSITE_COPY, 0, 0);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
}
I am getting an it rendered as:
How is $Image not an instance of imagick when it's defined as:
$im->resizeImage(500, 500, 0, 0, true);
What am I doing wrong and how do I fix it?
Alternative is cropping the image.
For Imagick this function: http://php.net/manual/en/imagick.cropimage.php
Imagick::cropImage — Extracts a region of the image
Steps:
Resize to format so width and height are minimal 500px
Crop with size of 500px
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);
I have a PHP script to re size image file as below;
$file = "test.bmp";
$ext = pathinfo($file, PATHINFO_EXTENSION);
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
$thumbname = "thumb/".$file_name.".".$ext;
$maxh = 200;
$maxw = 200;
$quality = 100;
list($width,$height)=getimagesize($file);
$src = imagecreatefromwbmp($file);
$tmp = imagecreatetruecolor($maxw,$maxh);
imagecopyresampled($tmp,$src,0,0,0,0,200,200,$width,$height);
imagejpeg($tmp,$thumbname,$quality);
imagedestroy($tmp);
The script is suppose to resize a Windows bitmap image to 200x200 thumbnail. But instead, I am getting a black 200x200 image. I am using PHP with Apache in Windows PC. How can I fix this?
.bmp and wbmp are VERY, VERY different file types.
Note the content-type headers:
Content-Type: image/x-xbitmap
Content-Type: image/vnd.wap.wbmp
Calling imagecreatefromwbmp($file) where $file is a .bmp will fail every time.
See this thread for info on how to load a .bmp file. It's not pretty.
As pointed out in PHP imagecopyresampled() docs:
Note:
There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().
To see if it's the case you can use imageistruecolor() and copy the contents to a new truecolor image before "copyresampling" it:
if( !imageistruecolor($src) ){
$newim = imagecreatetruecolor( $width, $height );
imagecopy( $newim, $src, 0, 0, 0, 0, $width, $height );
imagedestroy($src);
$src = $newim;
}
There is a new opensource project on Github that allows reading and saving of BMP files (and other file formats) in PHP.
The project is called PHP Image Magician.
<?php
//Create New 'Thumbnail' Image
$newImageWidth = 200;
$newImageHeight = 200;
$newImage = imagecreatetruecolor($newImageWidth, $newImageHeight);
$newImageFile = 'output.jpg';
$newImageQuality = 100;
//Load old Image(bmp, jpg, gif, png, etc)
$oldImageFile = "test.jpg";
//Specific function
$oldImage = imagecreatefromjpeg($oldImageFile);
//Non-Specific function
//$oldImageContent = file_get_contents($oldImageFile);
//$oldImage = imagecreatefromstring($oldImageContent);
//Get old Image's details
$oldImageWidth = imagesx($oldImage);
$oldImageHeight = imagesy($oldImage);
//Copy to new Image
imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newImageWidth, $newImageHeight, $oldImageWidth, $oldImageHeight);
//Output to file
imagejpeg($newImage, $newImageFile, $newImageQuality);
I'm working on an image resizer, to create thumbnails for my page. The resizer works on principle of include a DIRECT link to the image. But what I want to do is put in the PHP Variable in the URL string, so that it points to that file and resizes it accordingly.
My code is as follows :
<img src="thumbnail.php?image=<?php echo $row_select_property['image_url']; ?>
Image Resize :
<?php
// Resize Image To A Thumbnail
// The file you are resizing
$image = '$_GET[image_url]';
//This will set our output to 45% of the original size
$size = 0.45;
// This sets it to a .jpg, but you can change this to png or gif
header('Content-type: image/jpeg');
// Setting the resize parameters
list($width, $height) = getimagesize($image);
$modwidth = $width * $size;
$modheight = $height * $size;
// Creating the Canvas
$tn= imagecreatetruecolor($modwidth, $modheight);
$source = imagecreatefromjpeg($image);
// Resizing our image to fit the canvas
imagecopyresized($tn, $source, 0, 0, 0, 0, $modwidth, $modheight, $width, $height);
// Outputs a jpg image, you could change this to gif or png if needed
imagejpeg($tn);
?>
What I am trying to do is pass on the variable "image=" to the Thumbnail script. At the moment I am passing it through the URL string, but it doesnt seem to load the graphic.
I'll try expand on this more, should you have questions as I am finding it a little difficult to explain.
Thanks in advance.
I suspect at least part of the problem is that your existing...
$image = '$_GET[image_url]';
...line is creating a text string, rather than getting the contents of the 'image_url' query string. Additionally, your passing in the image name as "?image=" in the query string, so you should simply use "image", not "image_url".
As such, changing this to...
$image = $_GET['image'];
...should at least move things along.
Change it
$image = '$_GET[image_url]';
to
$image = $_GET['image'];
$image = '$_GET[image_url]';
should be
$image = $_GET['image'];