Cropping Image to larger than original size - php

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!

Related

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 imagecopyresampled fills whole destination image, but i need to fill only part

Source image width is 344 pixels and height is 86 pixels.
I create new blank image (destination) width 64 pixels and height also 64 pixels.
Then i want to resize source image, so that width is 64 pixels and height is proportionally less.
I did:
Get source image size.
$size = getimagesize( $_FILES['file_to_upload']['tmp_name'] );
Then set new width and height. Initial width is 344 pixels, i need 64, so new width is initial width divided with proportion (344 / 64). New height also is initial height divided with proportion.
$size[0] = $size[0]/($size[0]/64);
$size[1] = $size[1]/($size[0]/64);
Expecting that initial image resizes so that width will be 64 pixels and height 16 pixels.
Create initial image
$src = imagecreatefromstring(file_get_contents( $_FILES['file_to_upload']['tmp_name'] ));
Create destination image
$dst = imagecreatetruecolor($width_64,$height_64);
Create necessary image
imagecopyresampled($dst,$src,0,0,0,0,$width_64,$height_64,$size[0],$size[1]);
imagepng($dst, $img_directory. '/pngicon64_64.png' );
But as result i get this
But i nee to get this
As understand code does not resample initial image. Just take part of it.
May be instead of imagecopyresampled need to use something else?
You have to calculate the image ratio, check which dimension is greater & reduce that one to your desired size, then calculate the smaller dimension using the image ratio.
An extremely similar example is available in the PHP documenation for the imagecopyresampled function. I adapted that example to the code you provided:
// The file
$filename = $_FILES['file_to_upload']['tmp_name'];
// Set a maximum height and width
$width = 64;
$height = 64;
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);
$ratio_orig = $width_orig/$height_orig;
if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatetruecolor($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagepng($image_p, $img_directory. '/pngicon64_64.png');

Why is resized PNG image so much bigger than original image?

I am quite confused why PNG images that are resized using GD library are much bigger in size than the original.
This is the code I am using to resize the image:
// create image from posted file
$src = imagecreatefrompng($file['tmp_name']);
// get original size of uploaded image
list($width,$height) = getimagesize($file['tmp_name']);
if($width>$maxImgWidth) {
// resize the image to maxImgWidth, maintain the original aspect ratio
$newwidth = $maxImgWidth;
$newheight=($height/$width)*$newwidth;
$newImage=imagecreatetruecolor($newwidth,$newheight);
// fill transparent with white
/*$white=imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $white);*/
// the following is to keep PNG's alpha channels
// turn off transparency blending temporarily
imagealphablending($newImage, false);
// Fill the image with transparent color
$color = imagecolorallocatealpha($newImage,255,255,255,127);
imagefill($newImage, 0, 0, $color);
// restore transparency blending
imagesavealpha($newImage, true);
// do the image resizing by copying from the original into $newImage image
imagecopyresampled($newImage,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
// write image to buffer and save in variable
ob_start(); // Stdout --> buffer
imagepng($newImage,NULL,5); // last parameter is compression 0-none 9-best (slow), see also http://www.php.net/manual/en/function.imagepng.php
$newImageToSave = ob_get_contents(); // store stdout in $newImageToSave
ob_end_clean(); // clear buffer
// remove images from php buffer
imagedestroy($src);
imagedestroy($newImage);
$resizedFlag = true;
}
Then I save $newImageToSave as blob in mysql database.
I tried to prevent alpha channel and just set white background, no significant change in file size. I tried setting the "compression" parameters (0 to 9), but still bigger then the original.
Example
I took this image (1058px*1296px) and resized it to 900px * 1102px. These are the results:
Original File: 328 KB
PNG (0): 3,79 MB
PNG (5): 564 KB
PNG (9): 503 KB
Any tip how to get the resized image smaller in file size is appreciated.
--
PS: I thought it could be bit depth, but as you can see, the example image above has 32 bits, whereas the resized image is 24 bits.
You don't most of the functions you are calling to reduce the image , imagefill , imagealphablending etc can result to higher file size.
To Maintain the transparent use imagecreate instead of imagecreatetruecolor and just do a simple resize
$file['tmp_name'] = "wiki.png";
$maxImgWidth = 900;
// create image from posted file
$src = imagecreatefrompng($file['tmp_name']);
// get original size of uploaded image
list($width, $height) = getimagesize($file['tmp_name']);
if ($width > $maxImgWidth) {
$newwidth = $maxImgWidth;
$newheight = ($height / $width) * $newwidth;
$newImage = imagecreate($newwidth, $newheight);
imagecopyresampled($newImage, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($newImage, "wiki2.png", 5);
imagedestroy($src);
imagedestroy($newImage);
$resizedFlag = true;
}
Final Size : 164KB

centering image resource in new, larger image (PHP/imagecopy)

I'm trying to build a function that takes a PHP image resource and places it in the center of a new image of predetermined size. I do not want to scale the image; rather I want to place it as-is in the center of an enlarged "canvas."
$img is a valid image resource - if I return it I receive the correct original (unprocessed) image. $canvas_w and $canvas_h are the width and height of the desired new canvas. It's creating the correct size canvas, but the contents of the file are unexpectedly solid black when I return the desired "corrected" image resource ($newimg).
// what file?
$file = 'smile.jpg';
// load the image
$img = imagecreatefromjpeg($file);
// resize canvas (not the source data)
$newimg = imageCorrect($img, false, 1024, 768);
// insert image
header("Content-Type: image/jpeg");
imagejpeg($newimg);
exit;
function imageCorrect($image, $background = false, $canvas_w, $canvas_h) {
if (!$background) {
$background = imagecolorallocate($image, 255, 255, 255);
}
$img_h = imagesy($image);
$img_w = imagesx($image);
// create new image (canvas) of proper aspect ratio
$img = imagecreatetruecolor($canvas_w, $canvas_h);
// fill the background
imagefill($img, 0, 0, $background);
// offset values (center the original image to new canvas)
$xoffset = ($canvas_w - $img_w) / 2;
$yoffset = ($canvas_h - $img_h) / 2;
// copy
imagecopy($img, $image, $xoffset, $yoffset, $canvas_w, $canvas_h, $img_w, $img_h);
// destroy old image cursor
//imagedestroy($image);
return $img; // returns a black original file area properly sized/filled
//return $image; // works to return the unprocessed file
}
Any hints or obvious errors here? Thanks for any suggestions.
In place of imagecopy(), this seemed to work:
imagecopymerge($img, $image, $xoffset, $yoffset, 0,0, $img_w, $img_h, 100);

PHP GD - resizing image frame/canvas but not the actual image

I have an image with size 88x31 and would like to make it 100x100 without resizing the actual image but only its canvas/frame, maybe by copying it in the center of the new blank white image with 100x100 size. Any ideas how to do it?
The correct method is to create a new image and then copy the old image into the middle of it (assuming the starting image is is a JPEG and smaller than 100x100):
$oldimage = imagecreatefromjpeg($filename);
$oldw = imagesx($oldimage);
$oldh = imagesy($oldimage);
$newimage = imagecreatetruecolor(100, 100); // Creates a black image
// Fill it with white (optional)
$white = imagecolorallocate($newimage, 255, 255, 255);
imagefill($newimage, 0, 0, $white);
imagecopy($newimage, $oldimage, (100-$oldw)/2, (100-$oldh)/2, 0, 0, $oldw, $oldh);
You can see here: Thumbnail generation with PHP tutorial

Categories