how do i use imagecropauto() with IMG_CROP_TRANSPARENT? - php

When I try to crop transparant area of an image, its get to keep it original size, and the transparant areas are turned black.
If i run this code:
<?php
// Create a 300x300px transparant image with a 100px wide red circle in the middle
$i = imagecreatetruecolor(300, 300);
imagealphablending($i, FALSE);
imagesavealpha($i, TRUE);
$transparant = imagecolorallocatealpha($i, 0xDD, 0xDD, 0xDD, 0x7F);
imagefill($i, 0, 0, $transparant);
$red = imagecolorallocate($i, 0xFF, 0x0, 0x0);
imagefilledellipse($i, 150, 150, 100, 100, $red);
imagepng($i, "red_300.png");
// Crop away transparant parts and save
$i2 = imagecropauto($i, IMG_CROP_TRANSPARENT);
imagepng($i2, "red_crop_trans.png");
imagedestroy($i2);
// Crop away bg-color parts and save
$i2 = imagecropauto($i, IMG_CROP_SIDES);
imagepng($i2, "red_crop_sides.png");
imagedestroy($i2);
// clean up org image
imagedestroy($i);
I end up with a red_crop_trans.png image that is a 300x300px black image with an 100x100px red circle in it.
And a red_crop_sides.png that is a 100x100px black image with a 100x100px red circle in it.
Why is red_crop_trans.png not croped to 100x100px? and why is the background of both images black? And how do I crop them while keeping the transparace?

It took me a while to figure out what exactly was going on. It turned out $i2 = imagecropauto($i, IMG_CROP_TRANSPARENT); was returning false instead of true. According to the docs:
imagecropauto() returns FALSE when there is either nothing to crop or
the whole image would be cropped.
So instead of IMG_CROP_TRANSPARENT I used IMG_CROP_DEFAULT:
Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to
IMG_CROP_SIDES.
This gave me the expected result. Now I didn't get any black backgrounds myself. But it's a known issue so the solution was quite easily found:
imagecolortransparent($i, $transparant); // Set background transparent
And that brings me to the final completed code:
<?php
// Create a 300x300px transparant image with a 100px wide red circle in the middle
$i = imagecreatetruecolor(300, 300);
imagealphablending($i, FALSE);
imagesavealpha($i, TRUE);
$transparant = imagecolorallocatealpha($i, 0xDD, 0xDD, 0xDD, 0x7F);
imagecolortransparent($i, $transparant); // Set background transparent
imagefill($i, 0, 0, $transparant);
$red = imagecolorallocate($i, 0xFF, 0x0, 0x0);
imagefilledellipse($i, 150, 150, 100, 100, $red);
imagepng($i, "red_300.png");
// Crop away transparant parts and save
$i2 = imagecropauto($i, IMG_CROP_DEFAULT); //Attempts to use IMG_CROP_TRANSPARENT and if it fails it falls back to IMG_CROP_SIDES.
imagepng($i2, "red_crop_trans.png");
imagedestroy($i2);
// Crop away bg-color parts and save
$i2 = imagecropauto($i, IMG_CROP_SIDES);
imagepng($i2, "red_crop_sides.png");
imagedestroy($i2);
// clean up org image
imagedestroy($i);
?>

Related

Masking With A Grayscale Image With PHP And ImageMagick

I am trying to create a grayscale mask in Imagemagick (v7.0.11) that behaves like a layer mask in Photoshop where white areas are completely opaque and black areas are fully masked.
function grayscaleMaskTest () {
//Create a black and white mask
$mask = new Imagick();
$mask->newImage(300, 300, "#ffffff");
$mask->setImageType(IMAGICK::IMGTYPE_GRAYSCALE);
$mask->setImageFormat('gif');
//draw black circle
$draw = new ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor(new ImagickPixel("#000000"));
$draw->setFillColor(new ImagickPixel("#000000"));
$draw->circle(300/2, 300/2, 300/2, 300/2 + 100);
$mask->drawImage($draw);
//$mask->writeImage('C:\Users\Mike\Documents\images\mask.png'); //export mask
//Create final image
$final = new Imagick();
$final->newImage(300, 300, "#FF0000");
//Not sure if I had this right but tried writing the mask data to the alpha channel
//$final->compositeImage($mask, IMAGICK::COMPOSITE_COPYOPACITY, 0, 0, IMAGICK::CHANNEL_ALPHA);
$final->compositeImage($mask, IMAGICK::COMPOSITE_COPYOPACITY, 0, 0);
$final->writeImage('C:\Users\Mike\Documents\images\final.png');
}
The mask looks like this :
The desired result from this code if it worked would be this (minus the fake transparency) :
With help from #fmw42 this ended up working. Thanks!
//Create a black and white mask
$mask = new Imagick();
$mask->newImage(300, 300, "#ffffff");
//draw black circle
$draw = new ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor(new ImagickPixel("#0"));
$draw->setFillColor(new ImagickPixel("#0"));
$draw->circle(300/2, 300/2, 300/2, 300/2 + 100);
$mask->drawImage($draw);
$mask->setImageMatte(false); //<-------This got it going!
//Create final image
$final = new Imagick();
$final->newImage(300, 300, "#FF0000");
$final->compositeImage($mask, imagick::COMPOSITE_COPYOPACITY, 0, 0);`

Cropping Image to larger than original size

I am trying to crop an image, using some part of the image but also allowing for 'extra' space to be added around it. However when the cropped image generates black space in the 'extra' space, when I want it to be transparent.
Using cropper JavaScript to get crop coordinates: https://fengyuanchen.github.io/cropperjs/
Then use of PHP imagecopyresampled to crop the image to size.
The cropping of the image is fine, however if I crop an image to larger than the original size it adds black space around the image, I want to change this to transparent.
Looked into searching the croppped image for black pixels and converting them to transparent, however this idea breaks when the image has a black in it
Current php code: (asuming file type is PNG)
//$cropData
//is an array of data passed through from the cropper containing the original width and height, new width and height and the cropping x and y coordinates.
//passed in image to be cropped
$current_image = "/folder/example.jpg";
//image file location of cropped image
$image_name = "/folder/cropped_example.jpg";
//create blank image of desired crop size
$width = $cropData["width"];
$height = $cropData["height"];
$background = imagecreatetruecolor($width, $height);
//crop coordinates
$crop_x = $cropData["x"];
$crop_y = $cropData["y"];
//create resouce image of current image to be cropped
$image = imagecreatefrompng($current_image);
//crop image
imagecopyresampled($background, $image, 0, 0, $crop_x, $crop_y, $width, $height, $width, $height)){
imagepng($background, $image_name);
//File Uploaded... return to page
First you need to enable alpha channel by passing true to imagesavealpha
Next step is to disable alphablending by passing false to imagealphablending Otherwise the alpha channel will be used to recalculate colors and its value will be lost.
Allocate a transparent color passing 127 as alpha value to imagecolorallocatealpha
Fill the background of the source image by this color (e.g. calling imagefilledrectangle)
When passing source width and height parameters to imagecopyresampled do not exceed the real size of the image, otherwise out-of-bounds area will be assumed as opaque black.
Example:
$background = imagecreatetruecolor($width, $height);
//crop coordinates
$crop_x = 10;
$crop_y = 10;
imagesavealpha($background, true); // alpha chanel will be preserved
imagealphablending($background, false); // disable blending operations
$transparent_color = imagecolorallocatealpha($background, 0, 0, 0, 127); // allocate transparent
imagefilledrectangle($background, 0, 0, $width, $height, $transparent_color); // fill background
//create resouce image of current image to be cropped
$image = imagecreatefrompng($current_image);
// Limit source sizes;
$minw = min($width, imagesx($image));
$minh = min($height, imagesy($image));
//crop image
imagecopyresampled($background, $image, 0, 0, $crop_x, $crop_y, $minw, $minh, $minw, $minh);
imagepng($background, $image_name);
// done!

"How to fix" png image transparency

I created a white background and add a Png image. But upon doing trails & error still the png image show light backgroung color , it should be 100% transparent with no bg color.
This is my code after doing trails and error, but it still shows a ligh background color in png image. It should be 100% transparent. I tried a lot guys but not got any solutions upto now.
$img_h = imagesy($image);
$img_w = imagesx($image);
// create new image (canvas) of proper aspect ratio
$img = imagecreatetruecolor($canvas_w, $canvas_h);
$background = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $background);
$xoffset = ($canvas_w - $img_w) / 2;
$yoffset = ($canvas_h - $img_h) / 2;
imagealphablending($img, true);
imagesavealpha($img, true);
imagecopyresampled($img, $image, $xoffset, $yoffset, 0, 0, $img_w, $img_h, $img_w, $img_h);
I expected png image will be seen transparent on white background. But the code adds a light background color on png image.
Image preview -

Php GD adds black background around cropped source image

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);

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);

Categories