Resize an image in php with max height and width - php

Ok so I'm trying to resize an image using php. I do not have access to install plugins on the server I use at this time.
$originalimage is the actual original image that I'm going to resize.
$width is another parameter to define $original_width. The same can be said for $height and $original_height.
$original_width = imagesx($originalimage);
$original_height = imagesy($originalimage);
$max_width = $thumbwidth;
$max_height = $thumbheight;
$width = $original_width;
$height = $original_height;
Using the pre-setup above I start to work on this one here. This works but no way to set a max height. For example I pass a max width as $thumbwidth and max height as $thumbheight and this will work as desired till I then try to go ahead and use an image that's higher than it is wide. (Portrait image.) It does not completely fail however it does fail to enforce a max height, rendering an image that can potentially be very high.
if ($width > $height) {
$newwidth = $thumbwidth;
$divisor = $width / $thumbwidth;
$newheight = floor( $height / $divisor);
} else {
$newheight = $thumbheight;
$divisor = $height / $thumbheight;
$newwidth = floor( $width / $divisor );
}
$image = imagecreatetruecolor( $newwidth, $newheight );
imagecopyresampled( $image, $originalimage, 0, 0, 0, 0, $newwidth, $newheight, $original_width, $original_height );
After trying to understand this and failing after a few hours I came up with the code below which I had gotten from php.net. As you can see there was a reason I set two sets of variables equal to each other in the pre-setup part of the code. Mostly because I can not comprehend calling $max_width as $thumbwidth in the second code segment.
This below works as well until you pass in a parameter though that is larger than the width or height of $originalimage.
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image = imagecreatetruecolor( $width, $height );
imagecopyresampled( $image, $originalimage, 0, 0, 0, 0, $width, $height, $original_width, $original_height );
I'm sorry I can't find a way to do this on my own. As for this being a duplicate question, Most similar questions end up with "[Insert plugin name here] is better use that instead." I am asking specifically for an answer that does not use other plugins or javascript. (Besides GD which is pre-installed on my server.)
Before I end this question I will say that I am using imagejpeg($image); so the use of HTML or CSS is completely forbidden.

Here's a class I whipped up for a program I worked on. maybe it will help you?
<?php
class ImageHelper
{
/**
* #static
* #param $source string Path for source image
* #param $destination string Path for destination image to be placed
* #param $targetWidth int Width of the new image (in pixels)
* #param $targetHeight int Height of the new image (in pixels)
* #param $strict bool
*/
public static function createImage($source, $destination, $targetWidth, $targetHeight, $strict = false){
$dir = dirname($destination);
if(!is_dir($dir)){
mkdir($dir, 0770, true);
}
$fileContents = file_get_contents($source);
$image = imagecreatefromstring($fileContents);
$thumbnail = ImageHelper::resizeImage($image, $targetWidth, $targetHeight, $strict);
imagejpeg($thumbnail, $destination, 100);
imagedestroy($thumbnail);
imagedestroy($image);
}
/**
* Resize an image to the specified dimensions
* #param string $original Path to the original image
* #param int $targetWidth Width of the new image (in pixels)
* #param int $targetHeight Height of the new image (in pixels)
* #param bool $strict True to crop the picture to the specified dimensions, false for best fit
* #return bool|resource Returns the new image resource or false if the image was not resized.
*/
public static function resizeImage($original, $targetWidth, $targetHeight, $strict = false)
{
$originalWidth = imagesx($original);
$originalHeight = imagesy($original);
$widthRatio = $targetWidth / $originalWidth;
$heightRatio = $targetHeight / $originalHeight;
if(($widthRatio > 1 || $heightRatio > 1) && !$strict){
// don't scale up an image if either targets are greater than the original sizes and we aren't using a strict parameter
$dstHeight = $originalHeight;
$dstWidth = $originalWidth;
$srcHeight = $originalHeight;
$srcWidth = $originalWidth;
$srcX = 0;
$srcY = 0;
}elseif ($widthRatio > $heightRatio) {
// width is the constraining factor
if ($strict) {
$dstHeight = $targetHeight;
$dstWidth = $targetWidth;
$srcHeight = $originalHeight;
$srcWidth = $heightRatio * $targetWidth;
$srcX = floor(($originalWidth - $srcWidth) / 2);
$srcY = 0;
} else {
$dstHeight = ($originalHeight * $targetWidth) / $originalWidth;
$dstWidth = $targetWidth;
$srcHeight = $originalHeight;
$srcWidth = $originalWidth;
$srcX = 0;
$srcY = 0;
}
} else {
// height is the constraining factor
if ($strict) {
$dstHeight = $targetHeight;
$dstWidth = $targetWidth;
$srcHeight = $widthRatio * $targetHeight;
$srcWidth = $originalWidth;
$srcY = floor(($originalHeight - $srcHeight) / 2);
$srcX = 0;
} else {
$dstHeight = $targetHeight;
$dstWidth = ($originalWidth * $targetHeight) / $originalHeight;
$srcHeight = $originalHeight;
$srcWidth = $originalWidth;
$srcX = 0;
$srcY = 0;
}
}
$new = imagecreatetruecolor($dstWidth, $dstHeight);
if ($new === false) {
return false;
}
imagecopyresampled($new, $original, 0, 0, $srcX, $srcY, $dstWidth, $dstHeight, $srcWidth, $srcHeight);
return $new;
}
}

You can try this function as shown below.
<?php
function makeThumbnail($sourcefile,$max_width, $max_height, $endfile, $type){
// Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it
// and places it at endfile (path/to/thumb.jpg).
// Load image and get image size.
//
switch($type){
case'image/png':
$img = imagecreatefrompng($sourcefile);
break;
case'image/jpeg':
$img = imagecreatefromjpeg($sourcefile);
break;
case'image/gif':
$img = imagecreatefromgif($sourcefile);
break;
default :
return 'Un supported format';
}
$width = imagesx( $img );
$height = imagesy( $img );
if ($width > $height) {
if($width < $max_width)
$newwidth = $width;
else
$newwidth = $max_width;
$divisor = $width / $newwidth;
$newheight = floor( $height / $divisor);
}
else {
if($height < $max_height)
$newheight = $height;
else
$newheight = $max_height;
$divisor = $height / $newheight;
$newwidth = floor( $width / $divisor );
}
// Create a new temporary image.
$tmpimg = imagecreatetruecolor( $newwidth, $newheight );
imagealphablending($tmpimg, false);
imagesavealpha($tmpimg, true);
// Copy and resize old image into new image.
imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Save thumbnail into a file.
//compressing the file
switch($type){
case'image/png':
imagepng($tmpimg, $endfile, 0);
break;
case'image/jpeg':
imagejpeg($tmpimg, $endfile, 100);
break;
case'image/gif':
imagegif($tmpimg, $endfile, 0);
break;
}
// release the memory
imagedestroy($tmpimg);
imagedestroy($img);
}
?>
The function has five parameters.
> $sourcefile - Specicifies the temporary location of your image file
> $max_width - Specifies the possible maximum width
> $max_height - Specifies the possible maximum width
> $endfile - Specifies the directory to save the image
> $type - Specifies the image file type
Download demo code here

I've had a very similar problem building the thumbs for a gallery page. I tried Daniel Nyamasyo solution above but just could not get past the "$img = imagecreatefromjpeg($sourcefile);" line without getting "Warning: imagecreatefromjpeg failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request" no matter what $sourcefile I fed it.
I came up with this dirty method.
<?php
// Some variables
$thumb_width = 162; // The maximum values you want
$thumb_height = 122;
$thumb_pointer = 'thumbs'; // Put your output folder here which must exist
$img = imagecreatefromjpeg( $image_name);
$width = imagesx( $img );
$height = imagesy( $img );
if ($width>=$height)
{
// Now calculate thumbnail size
$new_width = $thumb_width;
$new_height = floor( $height * ($thumb_width / $width));
// The 'dirty' bit I found was needed for square or near square images
while ($new_height > $thumb_height)
{
$new_width = floor($new_width * 0.99);
$new_height = floor($new_height * 0.99);
}
}
else
{
$new_height = $thumb_height;
$new_width = floor($width * ($thumb_height / $height));
}
// Create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// Copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// Save the thumbnail into a file
imagejpeg( $tmp_img, $thumb_pointer.'/'.$image_name);
?>

Related

How to crop an image without losing its quality?

How to crop an image without losing its quality?
When I try to crop an image via admin panel, it works with no problems. But when I use the function "add_image_size" or "add_filter", thumbnails loss their quality.
These are the codes I tried.
set_post_thumbnail_size( 212, 159, array( 'center', 'center') );
add_image_size( 'qwqeq', 212, 159, array( 'center', 'center' ) );
add_filter('jpeg_quality', function($arg) { return 100; } );
How can I do this without using any plugin?
Here is a function to scale/crop an image using the php gd library. You can tinker with it to get it to do what you need.
function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){
$img = imagecreatefromstring(file_get_contents($filePath));
$dst_x = 0;
$dst_y = 0;
$width = imagesx($img);
$height = imagesy($img);
$newWidth = $newSize;
$newHeight = $newSize;
$aspectRatio = $width/$height;
if($width < $height){ //Portrait.
if($crop){
$newWidth = floor($width * ($newSize / $width));
$newHeight = floor($height * ($newSize / $width));
$dst_y = (floor(($newHeight - $newSize)/2)) * -1;
}else{
$newWidth = floor($width * ($newSize / $height));
$newHeight = $newSize;
$dst_x = floor(($newSize - $newWidth)/2);
}
} elseif($width > $height) { //Landscape
if($crop){
$newWidth = floor($width * ($newSize / $height));
$newHeight = floor($height * ($newSize / $height));
$dst_x = (floor(($newWidth - $newSize)/2)) * -1;
}else{
$newWidth = $newSize;
$newHeight = floor($height * ($newSize / $width));
$dst_y = floor(($newSize - $newHeight)/2);
}
}
$finalImage = imagecreatetruecolor($newSize, $newSize);
imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);
header('Content-Type: image/jpeg'); //<--Comment out if you want to save to file. Otherwise it will output to your browser.
imagejpeg($finalImage, $newPath, 60); //3rd param is quality. 60 does good job. You can play around.
imagedestroy($img);
imagedestroy($finalImage);
}
$filePath = 'path/to/image.jpg';
$newPath = NULL; //Set to NULL to output to browser. Otherwise set a new filepath to save.
$newSize = 400;
$crop = 1; //Set to NULL if you don't want to crop.
To use:
scaleMyImage($filePath, $newPath, $newSize, 1);

scale an image proportionally without knowing both dimensions

$newimg = imagecreatefromjpeg($tempname);
Now I need to scale this image proportionally but don't know both dimensions in advance.
$newimg = imagescale($newimg, 160, auto, IMG_BICUBIC); //doesn't work
or
$newimg = imagescale($newimg, auto, 160, IMG_BICUBIC); // doesn't work
Is there a way to say auto or something to calculate width or height automatically.
If no, how can I calculate this?
The accepted solution here doesn't work. I doesn't keep aspect ratio.
I made a function that will do what you need. I have tested this function with scaling down images and it works as intended.
This function will size an image preserving the aspect ratio to completely fit inside the dimensions that you specify. The image will also be centered.
The function also has the ability to crop. If you use the crop parameter, it will oversize the image to make sure the smallest side of the image fills the desired dimensions. It will then crop the image to fit inside the dimensions, thus completely filling the given dimensions. The image will be centered.
Here is the function:
function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){
$img = imagecreatefromstring(file_get_contents($filePath));
$dst_x = 0;
$dst_y = 0;
$width = imagesx($img);
$height = imagesy($img);
$newWidth = $newSize;
$newHeight = $newSize;
if($width < $height){ //Portrait.
if($crop){
$newWidth = floor($width * ($newSize / $width));
$newHeight = floor($height * ($newSize / $width));
$dst_y = (floor(($newHeight - $newSize)/2)) * -1;
}else{
$newWidth = floor($width * ($newSize / $height));
$newHeight = $newSize;
$dst_x = floor(($newSize - $newWidth)/2);
}
} elseif($width > $height) { //Landscape
if($crop){
$newWidth = floor($width * ($newSize / $height));
$newHeight = floor($height * ($newSize / $height));
$dst_x = (floor(($newWidth - $newSize)/2)) * -1;
}else{
$newWidth = $newSize;
$newHeight = floor($height * ($newSize / $width));
$dst_y = floor(($newSize - $newHeight)/2);
}
}
$finalImage = imagecreatetruecolor($newSize, $newSize);
imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($finalImage, $newPath, 60); //Set your compression.
imagedestroy($img);
imagedestroy($finalImage);
}
How to use:
$newSize = 160;
$filePath = 'path/myImg.jpg';
$newPath = 'path/newImg.jpg';
$crop = 1; //Set to NULL if you don't want to crop.
scaleMyImage($filePath, $newPath, $newSize, 1);
This should do exactly what you want with the crop parameter set to 1.
First of all you will have to mention al-least one dimension (either height or width) then using aspect ration of original image you can identify another. Here is a sample code which i used in my case:
$width = 160; // User-defined
$height = ''; // User-defined
$path = $uploadDir . '/' . $tempname;
$mime = getimagesize($path);
// Load original image
if($mime['mime']=='image/png') {
$orig_img = imagecreatefrompng($path);
}
if($mime['mime']=='image/jpg' || $mime['mime']=='image/jpeg' || $mime['mime']=='image/pjpeg') {
$orig_img = imagecreatefromjpeg($path);
}
// Get original image height and width
$width_orig = imagesx($orig_img);
$height_orig = imagesy($orig_img);
// Aspect ratio of original image
$aspectRatio = $width_orig / $height_orig;
// If any one dimension available then calculate other with the help of aspect-ratio of original image
if ($width == '' && $height != '') {
$newheight = $height;
$newwidth = round($height * $aspectRatio);
}
if ($width != '' && $height == '') {
$newheight = round($width / $aspectRatio);
$newwidth = $width;
}
$newimg = imagescale($orig_img, $newwidth, $newheight, IMG_BICUBIC);

GD Image resize doesn't work PHP

I've got the following piece of code:
$biggest = ($width > $height) ? $width : $height;
$newWidth = 0;
$newHeight = 0;
if($biggest > $divSize){
echo "BIGGEST<br />";
$scale = $divSize/$biggest;
$newWidth = floor($width * $scale);
$newHeight = floor($height * $scale);
} else if($biggest < $divSize){
echo "DIVSIZE<br />";
$scale = $biggest/$divSize;
$newWidth = floor($width * $scale);
$newHeight = floor($height * $scale);
}
echo "SCALE: ".$scale."<br />";
echo "BIGGEST: ".$biggest."<br />";
echo "WIDTH: ".$width."<br />";
echo "HEIGHT: ".$height."<br />";
echo "NEWWIDTH: ".$newWidth."<br />";
echo "NEWHEIGHT: ".$newHeight."<br />";
$sourceImage = imagecreatefromstring(file_get_contents($fileName));
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagedestroy($sourceImage);
This piece of code works fine for some images but not for all of them.
I've got a div with the dimension of 64 by 64.
For some images they scale perfectly fine but for some images the height of the outputted image is also 64px what should by for example 32px.
I don't have a clue what's causing this problem.
If you need more information, please ask.
Your function is good but sometimes your image should have a static size (this avoid to break design on some web pages).
In such a case, you can use this function. It resizes an image fit inside a defined width / height, and if the image has not the same proportions as the required thumbnail's, unused free space is set transparent.
function resizePreservingAspectRatio($img, $targetWidth, $targetHeight)
{
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);
// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight))
{
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
}
else if ($targetRatio > $srcRatio)
{
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
}
else
{
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}
// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);
// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);
// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled(
$targetImg, $img, ($targetWidth - $imgTargetWidth) / 2, // centered
($targetHeight - $imgTargetHeight) / 2, // centered
0, 0, $imgTargetWidth, $imgTargetHeight, $srcWidth, $srcHeight
);
return $targetImg;
}
Usage example :
$gd = imagecreatefromjpeg("images/image5.jpg");
$resized = resizePreservingAspectRatio($gd, 100, 100);
header("Content-type: image/png");
imagepng($resized);
This image :
Becomes :
Never mind.
I figured it out myself.
I simplefied the code for scaling the thumbnail quite a bit:
$biggest = ($width > $height) ? $width : $height;
$newWidth = 0;
$newHeight = 0;
$scale = ($biggest >= $thumbSize) ? $thumbSize/$biggest : $biggest/$thumbSize;
$newWidth = floor($width * $scale);
$newHeight = floor($height * $scale);
$sourceImage = imagecreatefromstring(file_get_contents($fileName));
$thumb = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($thumb, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagedestroy($sourceImage);
Maybe someone can use this.

Image resize PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can anybody suggest the best image resize script in php?
I'm still a newbie regarding image handling or file handling for that matter in PHP.
Would appreciate any input regarding the following
I post an image file using a simple html form and upload it via php.
When i try and alter my code to accomodate larger files (i.e. resize) I get an error.
Have been searching online but cant find anything really simple.
$size = getimagesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size == FALSE)
{
$errors=1;
}else if($size[0] > 300){ //if width greater than 300px
$aspectRatio = 300 / $size[0];
$newWidth = round($aspectRatio * $size[0]);
$newHeight = round($aspectRatio * $size[1]);
$imgHolder = imagecreatetruecolor($newWidth,$newHeight);
}
$newname= ROOTPATH.LOCALDIR."/images/".$image_name; //image_name is generated
$copy = imagecopyresized($imgHolder, $_FILES['image']['tmp_name'], 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
move_uploaded_file($copy, $newname); //where I want to move the file to the location of $newname
The error I get is:
imagecopyresized(): supplied argument
is not a valid Image resource in
Thanks in advance
Thanks for all your input, i've changed it to this
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$copy = imagecopyresized($imgHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $size[0], $size[1]);
if(!move_uploaded_file($copy, $newname)){
$errors=1;
}
Not getting a PHP log error but its not saving :(
Any ideas?
Thanks again
Result
Following works.
$oldImage = imagecreatefromjpeg($img);
$imageHolder = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresized($imageHolder, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($imageHolder, $newname, 100);
Thanks for everyones help
imagecopyresized takes an image resource as its second parameter, not a file name. You'll need to load the file first. If you know the file type, you can use imagecreatefromFILETYPE to load it. For example, if it's a JPEG, use imagecreatefromjpeg and pass that the file name - this will return an image resource.
If you don't know the file type, all is not lost. You can read the file in as a string and use imagecreatefromstring (which detects file types automatically) to load it as follows:
$oldImage = imagecreatefromstring(file_get_contents($_FILES['image']['tmp_name']));
$_FILES['image']['tmp_name'] is path not image resource. You have to use one of imagecreatefrom*() functions to create resource.
Here is my implementation of saving a thumbnail picture:
Resize and save function:
function SaveThumbnail($imagePath, $saveAs, $max_x, $max_y)
{
ini_set("memory_limit","32M");
$im = imagecreatefromjpeg ($imagePath);
$x = imagesx($im);
$y = imagesy($im);
if (($max_x/$max_y) < ($x/$y))
{
$save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
}
else
{
$save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
}
imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);
imagejpeg($save, $saveAs);
imagedestroy($im);
imagedestroy($save);
}
Usage:
$thumb_dir = "/path/to/thumbnaildir/"
$thumb_name = "thumb.jpg"
$muf = move_uploaded_file($_FILES['imgfile']['tmp_name'], "/tmp/test.jpg")
if($muf)
{
SaveThumbnail("/tmp/test.jpg", $thumb_dir . $thumb_name, 128, 128);
}
I use ImageMagick for stuff like that. Look how much simpler it is!
An example from one of my scripts:
$target= //destination path
move_uploaded_file($_FILES['item']['tmp_name'],$target);
$image = new imagick($target);
$image->setImageColorspace(imagick::COLORSPACE_RGB);
$image->scaleImage(350,0);
$image->writeImage($target);
You could then use getImageGeometry() to obtain the width and height.
For example:
$size=$image->getImageGeometry();
if($size['width'] > 300){ //if width greater than
$image->scaleImage(300,0);
}
Also, using scaleImage(300,0) means that ImageMagick automatically calculates the height based on the aspect ratio.
I was working on sth similar. I tried Ghostscript and ImageMagic. They are good tools but takes a but of time to set up. I ended up using 'sips' on a Snow Leopard server. Not sure if it's built in to Linux server but it's the faster solution I have found if you need sth done quick.
function resizeImage($file){
define ('MAX_WIDTH', 1500);//max image width
define ('MAX_HEIGHT', 1500);//max image height
define ('MAX_FILE_SIZE', 10485760);
//iamge save path
$path = 'storeResize/';
//size of the resize image
$new_width = 128;
$new_height = 128;
//name of the new image
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
$image_type = $file['type'];
$image_size = $file['size'];
$image_error = $file['error'];
$image_file = $file['tmp_name'];
$image_name = $file['name'];
$image_info = getimagesize($image_file);
//check image type
if ($image_info['mime'] == 'image/jpeg' or $image_info['mime'] == 'image/jpg'){
}
else if ($image_info['mime'] == 'image/png'){
}
else if ($image_info['mime'] == 'image/gif'){
}
else{
//set error invalid file type
}
if ($image_error){
//set error image upload error
}
if ( $image_size > MAX_FILE_SIZE ){
//set error image size invalid
}
switch ($image_info['mime']) {
case 'image/jpg': //This isn't a valid mime type so we should probably remove it
case 'image/jpeg':
$image = imagecreatefromjpeg ($image_file);
break;
case 'image/png':
$image = imagecreatefrompng ($image_file);
break;
case 'image/gif':
$image = imagecreatefromgif ($image_file);
break;
}
if ($new_width == 0 && $new_height == 0) {
$new_width = 100;
$new_height = 100;
}
// ensure size limits can not be abused
$new_width = min ($new_width, MAX_WIDTH);
$new_height = min ($new_height, MAX_HEIGHT);
//get original image h/w
$width = imagesx ($image);
$height = imagesy ($image);
//$align = 'b';
$zoom_crop = 1;
$origin_x = 0;
$origin_y = 0;
//TODO setting Memory
// generate new w/h if not provided
if ($new_width && !$new_height) {
$new_height = floor ($height * ($new_width / $width));
} else if ($new_height && !$new_width) {
$new_width = floor ($width * ($new_height / $height));
}
// scale down and add borders
if ($zoom_crop == 3) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$new_width = $width * ($new_height / $height);
} else {
$new_height = $final_height;
}
}
// create a new true color image
$canvas = imagecreatetruecolor ($new_width, $new_height);
imagealphablending ($canvas, false);
if (strlen ($canvas_color) < 6) {
$canvas_color = 'ffffff';
}
$canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
$canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
$canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
// Create a new transparent color for image
$color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
// Completely fill the background of the new image with allocated color.
imagefill ($canvas, 0, 0, $color);
// scale down and add borders
if ($zoom_crop == 2) {
$final_height = $height * ($new_width / $width);
if ($final_height > $new_height) {
$origin_x = $new_width / 2;
$new_width = $width * ($new_height / $height);
$origin_x = round ($origin_x - ($new_width / 2));
} else {
$origin_y = $new_height / 2;
$new_height = $final_height;
$origin_y = round ($origin_y - ($new_height / 2));
}
}
// Restore transparency blending
imagesavealpha ($canvas, true);
if ($zoom_crop > 0) {
$src_x = $src_y = 0;
$src_w = $width;
$src_h = $height;
$cmp_x = $width / $new_width;
$cmp_y = $height / $new_height;
// calculate x or y coordinate and width or height of source
if ($cmp_x > $cmp_y) {
$src_w = round ($width / $cmp_x * $cmp_y);
$src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
} else if ($cmp_y > $cmp_x) {
$src_h = round ($height / $cmp_y * $cmp_x);
$src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
}
// positional cropping!
if ($align) {
if (strpos ($align, 't') !== false) {
$src_y = 0;
}
if (strpos ($align, 'b') !== false) {
$src_y = $height - $src_h;
}
if (strpos ($align, 'l') !== false) {
$src_x = 0;
}
if (strpos ($align, 'r') !== false) {
$src_x = $width - $src_w;
}
}
// positional cropping!
imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
} else {
imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
}
//Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
if ( (IMAGETYPE_PNG == $image_info[2] || IMAGETYPE_GIF == $image_info[2]) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
}
$quality = 100;
$nameOfFile = 'resize_'.$new_width.'x'.$new_height.'_'.basename($file['name']);
if (preg_match('/^image\/(?:jpg|jpeg)$/i', $image_info['mime'])){
imagejpeg($canvas, $path.$nameOfFile, $quality);
} else if (preg_match('/^image\/png$/i', $image_info['mime'])){
imagepng($canvas, $path.$nameOfFile, floor($quality * 0.09));
} else if (preg_match('/^image\/gif$/i', $image_info['mime'])){
imagegif($canvas, $path.$nameOfFile);
}
}

Crop image in PHP

The code below crops the image well, which is what i want, but for larger images, it wotn work as well. Is there any way of 'zooming out of the image'
Idealy i would be able to have each image roughly the same size before cropping so that i would get good results each time
Code is
<?php
$image = $_GET['src']; // the image to crop
$dest_image = 'images/cropped_whatever.jpg'; // make sure the directory is writeable
$img = imagecreatetruecolor('200','150');
$org_img = imagecreatefromjpeg($image);
$ims = getimagesize($image);
imagecopy($img,$org_img, 0, 0, 20, 20, 200, 150);
imagejpeg($img,$dest_image,90);
imagedestroy($img);
echo '<img src="'.$dest_image.'" ><p>';
If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.
For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.
Here's a general formula for creating thumbnails:
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
Haven't tested this but it should work.
EDIT
Now tested and working.
imagecopyresampled() will take a rectangular area from $src_image of width $src_w and height $src_h at position ($src_x, $src_y) and place it in a rectangular area of $dst_image of width $dst_w and height $dst_h at position ($dst_x, $dst_y).
If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner.
This function can be used to copy regions within the same image. But if the regions overlap, the results will be unpredictable.
- Edit -
If $src_w and $src_h are smaller than $dst_w and $dst_h respectively, thumb image will be zoomed in. Otherwise it will be zoomed out.
<?php
$dst_x = 0; // X-coordinate of destination point
$dst_y = 0; // Y-coordinate of destination point
$src_x = 100; // Crop Start X position in original image
$src_y = 100; // Crop Srart Y position in original image
$dst_w = 160; // Thumb width
$dst_h = 120; // Thumb height
$src_w = 260; // Crop end X position in original image
$src_h = 220; // Crop end Y position in original image
// Creating an image with true colors having thumb dimensions (to merge with the original image)
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
// Get original image
$src_image = imagecreatefromjpeg('images/source.jpg');
// Cropping
imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
// Saving
imagejpeg($dst_image, 'images/crop.jpg');
?>
php 5.5 has an imagecrop function http://php.net/manual/en/function.imagecrop.php
$image = imagecreatefromjpeg($_GET['src']);
Needs to be replaced with this:
$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');
Because imagecreatefromjpeg() is expecting a string.
This worked for me.
ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php
HTML Code:-
enter code here
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
enter code here
<?php
$image = $_FILES;
$NewImageName = rand(4,10000)."-". $image['image']['name'];
$destination = realpath('../images/testing').'/';
move_uploaded_file($image['image']['tmp_name'], $destination.$NewImageName);
$image = imagecreatefromjpeg($destination.$NewImageName);
$filename = $destination.$NewImageName;
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
echo "cropped"; die;
?>
Improved Crop image functionality in PHP on the fly.
http://www.example.com/cropimage.php?filename=a.jpg&newxsize=100&newysize=200&constrain=1
Code in cropimage.php
$basefilename = #basename(urldecode($_REQUEST['filename']));
$path = 'images/';
$outPath = 'crop_images/';
$saveOutput = false; // true/false ("true" if you want to save images in out put folder)
$defaultImage = 'no_img.png'; // change it with your default image
$basefilename = $basefilename;
$w = $_REQUEST['newxsize'];
$h = $_REQUEST['newysize'];
if ($basefilename == "") {
$img = $path . $defaultImage;
$percent = 100;
} else {
$img = $path . $basefilename;
$len = strlen($img);
$ext = substr($img, $len - 3, $len);
$img2 = substr($img, 0, $len - 3) . strtoupper($ext);
if (!file_exists($img)) $img = $img2;
if (file_exists($img)) {
$percent = #$_GET['percent'];
$constrain = #$_GET['constrain'];
$w = $w;
$h = $h;
} else if (file_exists($path . $basefilename)) {
$img = $path . $basefilename;
$percent = $_GET['percent'];
$constrain = $_GET['constrain'];
$w = $w;
$h = $h;
} else {
$img = $path . 'no_img.png'; // change with your default image
$percent = #$_GET['percent'];
$constrain = #$_GET['constrain'];
$w = $w;
$h = $h;
}
}
// get image size of img
$x = #getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = #round($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
// autocompute width if only height is set
$w = (100 / ($sh / $h)) * .01;
$w = #round($sw * $w);
} elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
// get the smaller resulting image dimension if both height
// and width are set and $constrain is also set
$hx = (100 / ($sw / $w)) * .01;
$hx = #round($sh * $hx);
$wx = (100 / ($sh / $h)) * .01;
$wx = #round($sw * $wx);
if ($hx < $h) {
$h = (100 / ($sw / $w)) * .01;
$h = #round($sh * $h);
} else {
$w = (100 / ($sh / $h)) * .01;
$w = #round($sw * $w);
}
}
}
$im = #ImageCreateFromJPEG($img) or // Read JPEG Image
$im = #ImageCreateFromPNG($img) or // or PNG Image
$im = #ImageCreateFromGIF($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile($img);
} else {
// Create the resized image destination
$thumb = #ImageCreateTrueColor($w, $h);
// Copy from image source, resize it, and paste to image destination
#ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
//Other format imagepng()
if ($saveOutput) { //Save image
$save = $outPath . $basefilename;
#ImageJPEG($thumb, $save);
} else { // Output resized image
header("Content-type: image/jpeg");
#ImageJPEG($thumb);
}
}
You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)
Example:
<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
imagepng($im2, 'example-cropped.png');
imagedestroy($im2);
}
imagedestroy($im);
?>
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg'
Must be replaced with:
$image = imagecreatefromjpeg($_GET['src']);
Then it will work!

Categories