I'm using this jQuery plugin to crop images:
http://www.tmatthew.net/jwindowcrop
As you can see, it's really easy to use it on jQuery side, but my problem is with cropping the real image with PHP/GD.
with some goggling, I got:
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = 'demo_files/flowers.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r, null, $jpeg_quality);
But it's not taking care of zoom ins/zoom outs made by the jQuery plugin, how I should crop the image and save it using this plugin and PHP?
I figured this out, here is my code in case of anyone else has the same question, the cropping will be done by Zebra image class:
http://stefangabos.ro/php-libraries/zebra-image/#documentation
PHP:
// The variables we got from the plugin in upload page:
$x = intval($_POST['x']);
$y = intval($_POST['y']);
$w = intval($_POST['w']);
$h = intval($_POST['h']);
// The img file which we want to crop
$tmp_file = 'path/to/img';
// Now include the Zebra class
include_once('path/to/Zebra_Image.php');
$image = new Zebra_Image();
$image -> preserve_aspect_ratio = true;
$image -> enlarge_smaller_images = true;
$image -> preserve_time = true;
$image -> jpeg_quality = 100;
// Now imagine that the user has selected the area which he want with the plugin, and we also want to make the image out put in a specific size(200*225):
$target_path = 'new/img/path'; // the output img path
$image -> source_path = $tmp_file;
$image -> target_path = $target_path;
$image -> crop($x, $y, $x + $w, $y + $h);
$image -> source_path = $target_path;
$image -> resize(200, 225, ZEBRA_IMAGE_CROP_CENTER);
I am also using jwindowcrop. When you click jwindowcrop's zoom, the w and h changes. (see attached picture)
You have to make sure you used the correct parameters as stated in the php manual
http://www.php.net/manual/en/function.imagecopyresampled.php
In my case, I used imagecopyresized and I could crop the image properly including the zooms
dst_image
Destination image link resource.
src_image
Source image link resource.
dst_x
x-coordinate of destination point.
(in my case the destination image should start from upper left corner)
dst_y
y-coordinate of destination point.
(in my case the destination image should start from upper left corner)
src_x
x-coordinate of source point.
(the x-coordinate returned by the cropping function e.g. crop image from x=231, 231 pixels far from the left edge)
src_y
y-coordinate of source point.
(the x-coordinate returned by the cropping function e.g. crop image from y=706, 706 pixels far from the top edge)
dst_w
Destination width.
(in my case, my new image should have a width of 800px)
dst_h
Destination height.
(in my case, my new image should have a height of 400px)
src_w
Source width.
(when my cropping function zooms, it changes the width and height of the original image)
src_h
Source height.
(when my cropping function zooms, it changes the width and height of the original image)
imagecopyresized(dst_image, src_image, 0, 0, 231, 706, 800, 400, 521, 318);
Related
I’m creating an uploader that can upload jpg, giff and png images. Then converts them all too transparent PNG’s and then crops the image based on crop parameters send from client side. The crop can even supply negative axis coordinates, meaning the image is being cropped beyond image dimensions.
To ensure all supported formats can have transparency I first recreate the image into a transparent png, and this is working well.
//GET WIDTH AND HIEGHT OF UPLOADED JPG
list($imageWidth,$imageHeight)= getimagesize($originalDirectory.$file_name);
$image = imagecreatefromjpeg($originalDirectory.$file_name);
//CREATE NEW IMAGE BASED ON WIDTH AND HEIGHT OF SROUCE IMAGE
$bg = imagecreatetruecolor($imageWidth, $imageHeight);
//TRANSPARENCY SETTINGS FOR BOTH DESTINATION AND SOURCE IMAGES
$transparent2 = imagecolorallocatealpha($bg, 0, 0, 0, 127);
$transparent = imagecolorallocatealpha($image, 0,128,255,50); //ONLY TO ENSURE TRANSPARENCY IS WORKING
//SAVE TRANSPARENCY AMD FILL DESTINATION IMAGE
imagealphablending( $bg, false );
imagesavealpha($bg, true);
imagefill($bg, 0, 0, $transparent2);
//SAVE TRANSPARENCY AMD FILL SOURCE IMAGE
imagealphablending( $image, false );
imagesavealpha($image, true);
imagefill($image, 0, 0, $transparent); //ONLY TO ENSURE TRANSPARENCY IS WORKING
//CREATE AND SAVE AS PNG FILE WITH TRANSPARENCY
imagecopy($bg, $image, 0, 0, 0, 0, $imageWidth,$imageHeight);
header('Content-type: image/png');
imagepng($bg, $originalDirectory.$jpgFile);
imagedestroy($bg);
After the new png is created I use it to then only crop the image according to the parameters passed through from the client side scripting.
//GET NEWLY CREATED PNG
$src = imagecreatefrompng($originalSRC);
// NOT SURE IF NECESSARY BUT HAS NO EFFECT ON FINAL RESULT REGGARDLESS OF ANY SETTINGS DONE
imagealphablending( $image, false );
imagesavealpha($image, true);
//DEFINE DESTINATION CROPPED FILE
$thumbHighFilename = $thumbHighDirectory.'test.png';
//CREATE NEW IMAGE BASED ON FINAL CROP SIZE
$tmp = imagecreatetruecolor($cropWidth, $cropHeight);
//ENSURE DESTINATION HAS TRANSPARENT BACKGROUND
$transparent2 = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagefill($tmp, 0, 0, $transparent2);
/* -------------------------------------------------
PROBLEM HERE
When I try to merge the two with the crop paramaters
send from client side. All transparencies work, except
where crop X and Y axis exceeds source image paramaters.
Currently 50px offset on destination image is to verify
transparency works.
The source coordinates are based on image not crop area.
Tried with both imagecopyresized & imagecopyresampled
-------------------------------------------------*/
imagecopyresized($tmp, $src, -50,-50, $xAxis,$yAxis,$cropWidth, $cropHeight, $pW, $pH);
//SAVE FINAL IMAGE
header('Content-type: image/png');
imagepng($tmp, $thumbHighFilename);
imagedestroy($tmp);
This is where the source and destination images still has there transparency; however the negative coordinates creates a black background around the source image. How can I get that to be transparent?
While I found a lot about transparencies, nothing has been a proper solution. For example imagefill afterwards will not work as source could use 100% black around the edges and will make that also transparent then, which it shouldn’t.
CLIENT SIDE CROP EXAMPLE WITH INDICATIONS
CURRENT FINAL IMAGE RESULT WITH ADDED INDICATIONS
From what I could find it seems that there is no way for the GD imagecopyresized and imagecopyresampled to inherit the default backgrounds of the images it is cropping. Thus it keeps adding the default black background to the source image.
The biggest problem I’ve had was actually the crop container being responsive, thus very difficult to determine crop parameters.
To get around the problem I asked my frontend developer to send me more parameters from the crop. Below are all parameters now being passed to php, and the variables in php that are linked to the parameters received:
$xAxisCropper & $yAxisCropper – The variables get the X and Y
coordinates of the container not the image being cropped.
$pW & $pH – Defines the width and height of the crop box.
$containerWidth & $containerheight – As the container is responsive
getting the height and width helps understand what size the
coordinates where calculated on.
$imResizeHeight & $imResizeWidth – Since the images in the container
are always set to be contained within the container, it was important
to get the width and height into which the image is being resized by
the CSS. Giving understanding of what is happening with the image
within the responsive container.
$originalWidth & $originalHeight – Defines the original size of the
image and could either be passed to php or retrieved from the
original image uploaded to the server.
With these parameters I could now recreate the container with the image in the centre, and crop the newly created image. Before I crop it’s important to get the right scaling of the image for the crop, in order to ensure the best quality image is cropped and not compressed before cropping.
To do this I started by determining if the image in the container is being scaled up or down within the container. If scaled up image needs to be scaled to container size, if scaled down the container needs to be increased to have the image fit in the container. Below is the code that currently determines this, and changes the necessary parameters accordingly:
//IF CSS CONTAIN RESIZES HEIGHT EQUAL TO CROP CONTAINER HEIGHT
if($imResizeHeight == $containerheight){
//IF IMAGE SIZE WAS INCREASED
if($imResizeHeight>$originalHeight){
//DEFINE NEW IMAGE SIZE TO SCALE TO CONTAINER
$new_height = $imResizeHeight;
$new_width = $originalWidth * ($new_height / $originalHeight);
$scale = 'image'; //DEFINE WHAT IS BEING INCREASED
//ESLSE INCREASE CONTAINER TO IMAGE HEIGHT DIMENSIONS
}else{
//RECALCULATE WIDTH & HEIGHT OF CONTAINER
$newContainerWidth = $containerWidth * ($originalHeight / $containerheight);
$newContainerheight = $originalHeight;
$scale = 'container'; //DEFINE WHAT IS BEING INCREASED
}
//IF CSS CONTAIN RESIZES WIDTH EQUAL TO CROP CONTAINER WIDTH
}elseif($imResizeWidth == $containerWidth) {
//IF IMAGE SIZE WAS INCREASED
if($imResizeWidth>$originalWidth){
//DEFINE NEW IMAGE SIZE TO SCALE TO CONTAINER
$new_width = $imResizeWidth;
$new_height = $originalHeight * ($new_width / $originalWidth);
$scale = 'image'; //DEFINE WHAT IS BEING INCREASED
//ESLSE INCREASE CONTAINER TO IMAGE WIDTH DIMENSIONS
}else{
//RECALCULATE WIDTH & HEIGHT OF CONTAINER
$newContainerheight = $containerheight * ($originalWidth / $containerWidth);
$newContainerWidth = $originalWidth;
$scale = 'container'; //DEFINE WHAT IS BEING INCREASED
}
}
//IF IMAGE WAS INCREASED
if($scale=='image'){
//SCALE IMAGE
$src = imagescale ( $src , $new_width , $new_height, IMG_BILINEAR_FIXED);
imagepng($src,$originalSRC,0);
//ADD CHANGES TO VARIABLES USED IN CROP
$pH = $pH * ($new_height / $originalHeight);
$pW = max(0, round($pW * ($new_width / $originalWidth)));
$originalWidth = $new_width;
$originalHeight = $new_height;
$newContainerWidth = $containerWidth;
$newContainerheight = $containerheight;
//ELSE CONTAINER WAS INCREASED
}else {
//RECALCULATE COORDINATES OF CONTAINER
$yAxisCropper = max(0, round($yAxisCropper * ($newContainerheight / $containerheight)));
$xAxisCropper = max(0, round($xAxisCropper * ($newContainerWidth / $containerWidth)));
}
Once the parameters have been redefined according to the scaling, I then create the transparent background according to the container size and add the image in the centre. Thus creating a proper version of the crop container as an image, below the code for creating the new image:
//CALCULATE CENTRE OF NEW CONTAINER
$centreX = max(0, round(($newContainerWidth-$originalWidth)/2));
$centreY = max(0, round(($newContainerheight-$originalHeight)/2));
//CREATE NEW IMAGE BASED ON WIDTH AND HEIGHT OF SROUCE IMAGE
$bg = imagecreatetruecolor($newContainerWidth, $newContainerheight);
//SAVE TRANSPARENCY AMD FILL DESTINATION IMAGE
$transparent = imagecolorallocatealpha($bg, 0,0,0,127);
imagealphablending( $bg, false);
imagesavealpha($bg, true);
imagefill($bg, 0, 0, $transparent);
//CREATE AND SAVE AS PNG FILE WITH TRANSPARENCY
imagecopy($bg, $src, $centreX, $centreY, 0, 0, $originalWidth,$originalHeight);
header('Content-type: image/png');
imagepng($bg, $originalSRC, 0);
imagedestroy($bg);
The result till thus far:
It is only at this point that I send the new image to be cropped according to the specified width and height. Code below:
$src = imagecreatefrompng($originalSRC);
$thumbHighFilename = $thumbHighDirectory.$new_image;
$tmp = imagecreatetruecolor($cropWidth, $cropHeight);
$transparent2 = imagecolorallocatealpha($tmp, 0, 0, 0, 127);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagefill($tmp, 0, 0, $transparent2);
imagealphablending( $tmp, false );
imagesavealpha($tmp, true);
imagecopyresampled($tmp, $src, 0,0, $xAxisCropper,$yAxisCropper,$cropWidth, $cropHeight, $pW, $pH);
header('Content-type: image/png');
imagepng($tmp, $thumbHighFilename, 2);
Final result cropped 400x300
This has been the only way so far that I’ve managed to solve the problem. Code could probably still be optimised, but if someone has a more optimal solution please share.
I also wish to thank my frontend developer Salem for helping me to solve this irritating issue.
I also did have this annoying black Background Problem with png Files and the imagecropauto Function.
After "some" Tests, i have found a Solution as it seems. At least it works for me.
Here is my mofified Code:
$im=imagecreatefrompng("yourpicture.png");
$cropped=imagecropauto($im, IMG_CROP_SIDES);
imagesavealpha($cropped,true);
if($cropped !==false) {
imagedestroy($im);
$im=$cropped;
}
imagepng($im, "yourpicturecropped.png");
imagedestroy($im);
I'm am trying to add a 50px white margin down the right side of an image by creating an empty image that's 50px wider than the source image and then merging the source image onto it. The problem is that the source image just gets stretched sideways so it's 50px wider!
Maybe I'm using the wrong function to merge the images ...
here's my code
$destImage = $filepath;
#echo "dest image = ".$destImage;
$sourceImage = imagecreatefrompng($filepath);
// dimensions
$src_wide = imagesx($sourceImage);
echo "src_wide=".$src_wide;
$src_high = imagesy($sourceImage);
// new image dimensions with right padding
$dst_wide = $src_wide+50;
echo "dst_wide=".$dst_wide;
$dst_high = $src_high;
// New resource image at new size
$dst = imagecreatetruecolor($dst_wide, $dst_high);
// set white padding color
$clear = array('red'=>255,'green'=>255,'blue'=>255);
// fill the image with the white padding color
$clear = imagecolorallocate( $dst, $clear["red"], $clear["green"], $clear["blue"]);
imagefill($dst, 0, 0, $clear);
// copy the original image on top of the new one
imagecopymerge($dst,$sourceImage,0,0,0,0,$src_wide,$src_high, 100);
imagepng($dst,$destImage,6);
imagedestroy($dst);
chmod($destImage,0775);
what am I doing wrong here ??
thanks
It's stretching because you are copying it to the full width of the destination image. Instead use
imagecopyresampled($dst,$sourceImage,50,0,0,0,$src_wide,$src_high,$src_wide,$src_high);
I'm using a thumbnail script that is supposed to create thumbnails for images in my gallery directory. It works great. But one issue. The images are coming out rectangular instead of square. I need the images to come out square. I have the width set to 150 and the height set to 150. I'm not sure what I'm doing wrong. This is a pre-written script I am using that can be found at http://www.foliopages.com/php-photo-gallery-no-database [Not my site, this is the source of the script]
This is the first half of the thumbnail script(there are other functions in between these two parts):
$thumb_width = '150'; // width of thumbnails
$thumb_height = '150'; // height of thumbnails
$extensions = array(".jpg",".png",".gif",".JPG",".PNG",".GIF"); // allowed extensions in photo gallery
// create thumbnails from images
function make_thumb($folder,$src,$dest,$thumb_width) {
$source_image = imagecreatefromjpeg($folder.'/'.$src);
$width = imagesx($source_image);
$height = imagesy($source_image);
$thumb_height = floor($height*($thumb_width/$width));
$virtual_image = imagecreatetruecolor($thumb_width,$thumb_height);
imagecopyresampled($virtual_image,$source_image,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
imagejpeg($virtual_image,$dest,100);
}
And the second part:
$thumb = $src_folder.'/thumbs/'.$file;
if (!file_exists($thumb)) {
make_thumb($src_folder,$file,$thumb,$thumb_width);
}
The issue is that you calculate a value for $thumb_height in the line
$thumb_height = floor($height*($thumb_width/$width));
Replace that line with this one to make the thumb square:
$thumb_height=$thumb_width;
Having a few teething problems watermarking a photo. It all works fine apart from the watermarked photo's colors become duller than they should be - very noticeable in-fact.
I'm using imagecopyresized to do my watermarking, as this specifically allows me to use PNG-24 watermarks, the others do not. I know the colors are usually OK, as I have just used readfile($url) as a test, and the photos are perfect.
Here is my script:
<?php
// get parent and watermark images & sizes
$image = imagecreatefromjpeg($url);
$imageSize = getimagesize($url);
$watermark = imagecreatefrompng('watermark.png');
$watermark_o_width = imagesx($watermark);
$watermark_o_height = imagesy($watermark);
// calculate new watermark width and position
if ($imageSize[0] > $imageSize[1] || $imageSize[0] == $imageSize[1]) {
$leftPercent = 23;
} else {
$leftPercent = 7;
}
$leftPixels = ($imageSize[0]/100)*$leftPercent;
$newWatermarkWidth = $imageSize[0]-$leftPixels;
$newWatermarkHeight = $watermark_o_height * ($newWatermarkWidth / $watermark_o_width);
// place watermark on parent image, centered and scaled
imagecopyresized(
$image,
$watermark,
$imageSize[0]/2 - $newWatermarkWidth/2,
$imageSize[1]/2 - $newWatermarkHeight/2,
0,
0,
$newWatermarkWidth,
$newWatermarkHeight,
imagesx($watermark),
imagesy($watermark)
);
// print
imagejpeg($image);
// destroy
imagedestroy($image);
imagedestroy($watermark);
?>
How can I stop this from happening? I'm reading about imagecreatetruecolor, does that solve the issue? I'm Googling "imagecreatetruecolor color loss photos" and variations but nobody really talks about this issue. If I do need this function, where would I add that to this script?
This has totally thrown a spanner in the works for me and would love for somebody to tell me where to stick it (not literally).
Here is an example of the color loss. The preview image should be exactly the same colors as the thumbnail. The thumbnails are created using readfile() whereas the previews are created using imagecreatefromjpeg and imagecopresized.
This example code works fine, by using the same characteristics as your images:
Original JPG: dark background; beautiful girl; red dress.
Watermark PNG: transparent background; text; gray color.
<?php
// Path the the requested file (clean up the value if needed)
$path = $url;
// Load image
$image = imagecreatefromjpeg($path);
$w = imagesx($image);
$h = imagesy($image);
// Load watermark
$watermark = imagecreatefrompng('watermark.png');
$ww = imagesx($watermark);
$wh = imagesy($watermark);
// Merge watermark upon the original image (center center)
imagecopy($image, $watermark, (($w/2)-($ww/2)), (($h/2)-($wh/2)), 0, 0, $ww, $wh);
// Output the image to the browser
header('Content-type: image/jpeg');
imagejpeg($image);
// destroy both images
imagedestroy($image);
imagedestroy($watermark);
// kill script
exit();
?>
Left: Output Image | Right: Original Image
Note:
The output image was compressed several times until: Original -> PHP Output -> GIMP -> Here.
After much testing, I came to the conclusion that PHP's GD Image does not support color profiles on the images that are being watermarked. I am now using Imagick and the colors are perfect.
How can I take a 500x500 (or any sized) image that has been uploaded to the server and generate a new image from defined specific x,y coordinates? For example (0,0) to (50,0); (0,50) to (50,50). Rather than resizing an image down to 50x50px, I want to grab the top left part of an image and in a sense "crop" it to use as a thumbnail.
How can I go about doing this in PHP?
You want to use imagecopy. First create an image with the dimensions you want and then use imagecopy to a portion of the source image into the new image:
// use whatever mechanism you prefer to load your source image into $image
$width = 50;
$height = 50;
// Define your starting coordinates in the source image.
$source_x = 20;
$source_y = 100;
$new_image = imagecreatetruecolor($width, $height);
imagecopy($new_image, $image, 0, 0, $source_x, $source_y, $width, $height);
// Now $new_image has the portion cropped from the source and you can output or save it.
imagejpeg($new_image);
http://www.php.net/manual/en/function.imagick-cropthumbnailimage.php#81547
$image = new Imagick($path."test1.jpg");
$image->cropThumbnailImage(160,120); // Crop image and thumb
$image->writeImage($path."test1.jpg");
I've seen a few ways to do this. If you want to generate the thumbs on the fly you could use:
function make_thumb($src,$dest,$desired_width)
{
/* read the source image */
$source_image = imagecreatefromjpeg($src);
$width = imagesx($source_image);
$height = imagesy($source_image);
/* find the "desired height" of this thumbnail, relative to the desired width */
$desired_height = floor($height*($desired_width/$width));
/* create a new, "virtual" image */
$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
/* copy source image at a resized size */
imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
/* create the physical thumbnail image to its destination */
imagejpeg($virtual_image,$dest);
}
You can also set the quality parameter in the imagejpeg function.
Or if you want to save the image thumb to a directory I would look at:
http://bgallz.org/270/php-create-thumbnail-images/
or
http://www.imagemagick.org/script/index.php