how to resize image proportionally in php - php

I would like to resize an image proportionally to 500px X 500px I found the below code from the net however the article didn't have an example of how to use the script, can someone just get me started on how to display the resized image?
$filename = 'test.png';
list($width, $height, $type, $attr) = getimagesize($filename);
$orig_w = $width;
$orig_h = $height;
$MIN_W = 500;
$MIN_H = 500;
$MAX_H = 500;
$MAX_W = 500;
function image_resize_up($orig_w, $orig_h, $MIN_W, $MIN_H){
$ratio = $orig_w * 1.0 / $orig_h;
$w_undersized = ($orig_w < $MIN_W);
$h_undersized = ($orig_h < $MIN_H);
if ($w_undersized OR $h_undersized)
{
$new_w = round( max($MIN_W, $ratio * $MIN_H) );
$new_h = round( max($MIN_H, $MIN_W / $ratio) );
return array('width' => $new_w, 'height' => $new_h);
}
return null;
}
function image_resize_down($orig_w, $orig_h, $MAX_W, $MAX_H){
$ratio = $orig_w * 1.0 / $orig_h;
$w_undersized = ($orig_w > $MAX_W);
$h_undersized = ($orig_h > $MAX_H);
if ($w_undersized OR $h_undersized)
{
$new_w = round( min($MAX_W, $ratio * $MAX_H) );
$new_h = round( min($MAX_H, $MAX_W / $ratio) );
return array('width' => $new_w, 'height' => $new_h);
}
return null;
}
echo $w_undersized;
I tried
echo "<img src=".$filename.$new_w.$new_h.">";//gives me undefined variable and the image isn't resized.

You have wrongly defined your attributes try that:
echo "<img src='".$filename."' style='width:".$new_w."; height:".$new_h."; '>";
Good Luck

First you need a function to crop the image so that width and height are equal:
function crop_image_square($filename, $_filename){
list($width, $height, $type) = getimagesize($filename);
$min = min($width, $height);
$x = ($width > $height) ? ($width-$height)/2 : 0;
$y = ($width < $height) ? ($height-$width)/2 : 0;
switch($type){
case IMG_GIF: $src = imagecreatefromgif($filename); break;
case IMG_JPG: $src = imagecreatefromjpeg($filename); break;
case IMG_PNG: $src = imagecreatefrompng($filename); break;
// and so on...
}
$dest = imagecreatetruecolor($min, $min);
imagecopy($dest, $src, 0, 0, $x, $y, $width, $height);
switch($type){
case IMG_GIF: imagegif($dest, $_filename); break;
case IMG_JPG: imagejpeg($dest, $_filename); break;
case IMG_PNG: imagepng($dest, $_filename); break;
// and so on...
}
imagedestroy($src);
imagedestroy($dest);
}
Then you may apply the function to one or more image(s):
crop_image_square("image_01.jpg", "image_01_cropped.jpg");
crop_image_square("image_02.jpg", "image_02_cropped.jpg");
crop_image_square("image_03.jpg", "image_03_cropped.jpg");
The PHP part is done. Displaying a resized version can be easily achieved with plain HTML, as you’ve pointed out:
<img src="image_01_cropped.jpg" width="500" height="500"/>
<img src="image_02_cropped.jpg" width="500" height="500"/>
<img src="image_03_cropped.jpg" width="500" height="500"/>

Working with images in PHP/GD can be tedious, which is why I wrote the SimpleImage library to make things less painless. It resolves many edge cases and gotchas that come with GD image manipulation.
Here's how to resize an image proportionally to fit in a 500x500 box:
// Load the image from image.jpg
$image = new \claviska\SimpleImage('image.jpg');
// Proportionally resize to fit inside a 500x500 box and save to result.jpg
$image->bestFit(500, 500)->toFile('result.jpg');
SimpleImage can be installed via Composer or linked manually. Details in the readme.

If you would like, you can use the library SimpleImage.
include('src/abeautifulsite/SimpleImage.php'); //Load the SimpleImage
$image = new SimpleImage(); //Create an instance.
$image->load('picture.jpg'); //Load the picture.jpg.
image->resize(500, 500); //Resize.
$image->save('picture2.jpg');//Save as picture2.jpg.

Related

imagesx() expects parameter 1 to be resource, string given

I try to upload multiple files to my bucket earlier it worked well but now I try to resize and compress the image before upload, it throws error imagesx() expects parameter 1 to be resource, string given here is the code :
foreach($_FILES as $ind => $filegroup){
$count=0;
foreach($_FILES[$ind]['name']as $actfile){
$tmp=$_FILES[$ind]['tmp_name'][$count];
$count=$count + 1;
$newind= str_replace('_',' ',$ind);
$filenamenew= $insertedids[0].$newind."_".$count.".jpg";
$temp='menu_images/'.$filenamenew;
$im = imagecreatetruecolor(700, 700);
$bg = imagecolorallocate ( $im, 255, 255, 255 );
imagefilledrectangle($im,0,0,700,700,$bg);
$max_width=700;
$max_height= 700;
$width = imagesx($tmp);
$height = imagesy($tmp);
# 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;
}
$im2 = imagescale($tmp, $width, $height);
imagecopy($im, $im2, (imagesx($im)/2)-(imagesx($im2)/2), (imagesy($im)/2)-(imagesy($im2)/2), 0, 0, imagesx($im2), imagesy($im2));
imagejpeg($im, NULL , 70);
I am trying to upload this final $im to bucket , I have already installed gd library in my cent os
imagesx() expects an image resource as parameter, returned by one of the image creation functions for example imagecreatetruecolor(). If you need the height or width of of an image, you can use getimagesize() like below.
list( $width, $height ) = getimagesize( 'filepath' );
Try this:
...
foreach($_FILES[$ind]['name'] as $fid => $actfile){ // add $fid in here!
...
list($width, $height) = getimagesize($tmp=$_FILES[$ind]['tmp_name'][$fid]);
echo "width: $width; height: $height<br />\n";
...
}
...
The key problem was posting sourcefile to s3 bucket I changed that to body , also I changed my php settings to allow file upload till 5 mb
Here is the solution:
$im = imagecreatetruecolor(700, 700);
$bg = imagecolorallocate ( $im, 255, 255, 255 );
imagefilledrectangle($im,0,0,700,700,$bg);
list( $width, $height , $image_type ) = getimagesize($tmp);
$max_width=700;
$max_height= 700;
# 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;
}
switch ($image_type)
{
case 1: $im3 = imagecreatefromgif($tmp); break;
case 2: $im3 = imagecreatefromjpeg($tmp); break;
case 3: $im3 = imagecreatefrompng($tmp); break;
default: return ''; break;
}
$im2 = imagescale($im3, $width, $height);
imagecopy($im, $im2, (imagesx($im)/2)-(imagesx($im2)/2), (imagesy($im)/2)-(imagesy($im2)/2), 0, 0, imagesx($im2), imagesy($im2));
$imgdata = image_data($im);
function image_data($gdimage)
{
ob_start();
imagejpeg($gdimage,NULL,70);
return(ob_get_clean());
}
And while uploading to bucket
$result = $s3->putObject([
'Bucket' => 'yourbucket',
'Key' => 'filename',
'Body' => $imgdata
]);

Saving a jpg as a transparent png with php

I have a function created which processes images in different ways based on the parameters. I have comments in the function to explain a bit.
Everything works with exception to when I take a jpg image and save it as a png. I just checked, even if I use imagepng() but save it with the extension .jpg, the image displays while properly resized, but with a .jpg extension. However, if I upload the same .jpg image, use imagepng() and save it with a .png extension, I get an image of the expected width and height after the resize, in a png format, with a .png extension. While the whole image is 100% transparent I have a 1px by 1px black pixel in the top left corner.
I would appreciate it if anyone can look at this and see if they see something I am missing. I believe the 1px X 1px is coming from the point I use for the imagefill(), but I don't understand why; it should be filling all transparent as with the rest of the image.
Here is my function:
if(!function_exists("upload")){
//$image = $image file name
//$width = intended width of resized image, if 0 it will proportion to height, overrides proportion
//$height = intended width of resized image, if 0 it will proportion to width, overrides proportion
//$proportion = 2,1,0;
//------ 2 = Preserve proportions while adding a border to fill width and height
//------ 1 = retain proportion to fit within both given width and height
//------ 0 = disregard proportions and resize to the exact width and height
function upload($image, $width, $height, $proportion){
// IS GD HERE?
$gdv = get_gd_info();
if (!$gdv){
return FALSE;
}
// GET AN IMAGE THING
$ext = trim(strtolower(end(explode('.', $image))));
list($imageX, $imageY, $type) = getimagesize($image); //gets information about new server image
// GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS
$ratio_w = ($width / $imageX);
$ratio_h = ($height / $imageY);
$ratio = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;
if($width == 0){
if($imageY > $height){
$newHeight = $height;
$newWidth = ($height/$imageY) * $imageX;
}else{
$newHeight = $imageY;
$newWidth = $imageX;
}
$width = $newWidth;
$height = $newHeight;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = 0;
$fromMidY = 0;
}elseif($height == 0){
if ($imageX > $width){
$newWidth = $width;
$newHeight = ($width/$imageX) * $imageY;
}else{
$newHeight = $imageY;
$newWidth = $imageX;
}
$width = $newWidth;
$height = $newHeight;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = 0;
$fromMidY = 0;
}elseif($proportion == 2){
// COMPUTE THUMBNAIL IMAGE DIMENSIONS
$newWidth = $imageX * $ratio;
$newHeight = $imageY * $ratio;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = ($width - $newWidth) / 2.0;
$fromMidY = ($height - $newHeight) / 2.0;
}elseif($proportion == 1){
if ($imageX > $width){
$newHeight = ($width/$imageX) * $imageY;
$newWidth = $width;
}
if ($imageY > $height){
$newHeight = $height;
$newWidth = ($height/$imageY) * $imageX;
}
$fromMidY = 0;
$fromMidX = 0;
}elseif($proportion == 0){
$newWidth = $width;
$newHeight = $height;
$fromMidY = 0;
$fromMidX = 0;
}
switch(strtoupper($ext))
{
case 'JPG' :
case 'JPEG' :
$source = imagecreatefromjpeg($image);
break;
case 'PNG' :
$source = imagecreatefrompng($image);
break;
default : die("UNKNOWN IMAGE TYPE: $image");
}
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
if ($gdv >= 2)
{
// IF GD IS AT LEVEL 2 OR ABOVE
$target = imagecreatetruecolor($width, $height);
$color = imagecolorallocatealpha($target, 0, 0, 0, 127);
imagefill($target, 0, 0, $color);
imagesavealpha($target, TRUE);
imagecopyresampled ($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY);
}
else
{
// IF GD IS AT A LOWER REVISION LEVEL
$target = imagecreate($width, $height);
imagesavealpha($target, TRUE);
$empty = imagecolorallocatealpha($thumb,0x00,0x00,0x00,127);
imagefill($target, 0, 0, $empty);
imagecopyresized($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY);
}
// SHARPEN THE PIC
$sharpenMatrix = array
( array( -1.2, -1, -1.2 )
, array( -1, 20, -1 )
, array( -1.2, -1, -1.2 )
)
;
$divisor = array_sum(array_map('array_sum', $sharpenMatrix));
$offset = 0;
imageconvolution($target, $sharpenMatrix, $divisor, $offset);
if(imagepng($target, $image,9)){
imagedestroy($target);
}else{
}
return $image;
}
}
EDIT 1: I guess I should have noted that I am uploading a .jpg image (Ex: 100px X 200px) and converting them to .png (Ex: 400px X 200px) but am retaining the proportions of the image to fit perfectly in the center of the destination .png. So I would have a 400px X 200px .png with my image in the center and 100px on the left and right which should be transparent. This way it fits nicely in a slider without a solid color as a fill. So an example of my call to my function would be upload($image, 400, 200, 2).
I figured out what the issue was. The portion of code which decides whether I should use imagecreatefromjpeg or imagecreatefrompng was incorrectly going off of the extension of the passed image and NOT by its mime type. I switched it to this:
switch($type)
{
case '2' :
$source = imagecreatefromjpeg($image);
break;
case '3' :
$source = imagecreatefrompng($image);
break;
default : die("UNKNOWN IMAGE TYPE: $image");
}
where $type is coming from the line I had in there
list($imageX, $imageY, $type) = getimagesize($image);
So all together the function is:
if(!function_exists("upload")){
//$image = $image file name
//$width = intended width of resized image, if 0 it will proportion to height, overrides proportion
//$height = intended width of resized image, if 0 it will proportion to width, overrides proportion
//$proportion = 2,1,0;
//------ 2 = Preserve proportions while adding a border to fill width and height
//------ 1 = retain proportion to fit within both given width and height
//------ 0 = disregard proportions and resize to the exact width and height
function upload($image, $width, $height, $proportion){
// IS GD HERE?
$gdv = get_gd_info();
if (!$gdv){
return FALSE;
}
// GET AN IMAGE THING
$ext = trim(strtolower(end(explode('.', $image))));
list($imageX, $imageY, $type) = getimagesize($image); //gets information about new server image
// GET THE LESSER OF THE RATIO OF THUMBNAIL H OR W DIMENSIONS
$ratio_w = ($width / $imageX);
$ratio_h = ($height / $imageY);
$ratio = ($ratio_w < $ratio_h) ? $ratio_w : $ratio_h;
if($width == 0){
if($imageY > $height){
$newHeight = $height;
$newWidth = ($height/$imageY) * $imageX;
}else{
$newHeight = $imageY;
$newWidth = $imageX;
}
$width = $newWidth;
$height = $newHeight;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = 0;
$fromMidY = 0;
}elseif($height == 0){
if ($imageX > $width){
$newWidth = $width;
$newHeight = ($width/$imageX) * $imageY;
}else{
$newHeight = $imageY;
$newWidth = $imageX;
}
$width = $newWidth;
$height = $newHeight;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = 0;
$fromMidY = 0;
}elseif($proportion == 2){
// COMPUTE THUMBNAIL IMAGE DIMENSIONS
$newWidth = $imageX * $ratio;
$newHeight = $imageY * $ratio;
// COMPUTE THUMBNAIL IMAGE CENTERING OFFSETS
$fromMidX = ($width - $newWidth) / 2.0;
$fromMidY = ($height - $newHeight) / 2.0;
}elseif($proportion == 1){
if ($imageX > $width){
$newHeight = ($width/$imageX) * $imageY;
$newWidth = $width;
}
if ($imageY > $height){
$newHeight = $height;
$newWidth = ($height/$imageY) * $imageX;
}
$fromMidY = 0;
$fromMidX = 0;
}elseif($proportion == 0){
$newWidth = $width;
$newHeight = $height;
$fromMidY = 0;
$fromMidX = 0;
}
switch($type)
{
case '2' :
$source = imagecreatefromjpeg($image);
break;
case '3' :
$source = imagecreatefrompng($image);
break;
default : die("UNKNOWN IMAGE TYPE: $image");
}
// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
if ($gdv >= 2)
{
// IF GD IS AT LEVEL 2 OR ABOVE
$target = imagecreatetruecolor($width, $height);
$color = imagecolorallocatealpha($target, 0, 0, 0, 127);
imagefill($target, 0, 0, $color);
imagesavealpha($target, TRUE);
imagecopyresampled ($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY);
}
else
{
// IF GD IS AT A LOWER REVISION LEVEL
$target = imagecreate($width, $height);
imagesavealpha($target, TRUE);
$empty = imagecolorallocatealpha($thumb,0x00,0x00,0x00,127);
imagefill($target, 0, 0, $empty);
imagecopyresized($target, $source, $fromMidX, $fromMidY, 0, 0, $newWidth, $newHeight, $imageX, $imageY);
}
// SHARPEN THE PIC
$sharpenMatrix = array
( array( -1.2, -1, -1.2 )
, array( -1, 20, -1 )
, array( -1.2, -1, -1.2 )
)
;
$divisor = array_sum(array_map('array_sum', $sharpenMatrix));
$offset = 0;
imageconvolution($target, $sharpenMatrix, $divisor, $offset);
if(imagepng($target, $image,9)){
imagedestroy($target);
}
return $image;
}
}
And an example call would be: upload("path/to/image/on/server.png", 400, 200, 2)
Where the image path can be either in a jpg or png mime type. But the extension MUST be .png. I suppose I can make it smarter where you can have any extension, but with the current code which uses this function it makes more sense for me to leave it as is. I would like to eventually add the option to turn on or off the transparency and instead use a solid color such as black if it is needed. Feel free to use and modify this.
There are nice hex2rgb/rgb2hex functions which I plan on using for this here

Changing image width when sending via header in php

I have this piece of code that calls a random image and sends it to another page. That page calls this script via an image link. What I am trying to figure out is how to make it specify an image width when the image is past my max width. I got this far then got completely lost.
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1;
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
if (preg_match('/\.'.$ext.'$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double)microtime()*1000000);
$rand = mt_rand(0, $i);
$image =($folder.$files[$rand]);
if (file_exists($image))
{
list($width) = getimagesize($image);
$maxWidth = 150;
if ($width > $maxWidth)
{
header('Location: '.$folder.$files[$rand]); // Voila!;
}
else
{
header('Location: '.$folder.$files[$rand]); // Voila!
}
}
?>
You could use CSS max-width and max-height properties.
Here isa couple of resize functions, I think at least one of them maintains the aspect ratio.
function resize_image($file, $w, $h, $crop = false) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
And:
function thumb_aspect_crop($source_path, $desired_width, $desired_height) {
list( $source_width, $source_height, $source_type ) = getimagesize($source_path);
switch ($source_type) {
case IMAGETYPE_GIF:
$source_gdim = imagecreatefromgif($source_path);
break;
case IMAGETYPE_JPEG:
$source_gdim = imagecreatefromjpeg($source_path);
break;
case IMAGETYPE_PNG:
$source_gdim = imagecreatefrompng($source_path);
break;
}
$source_aspect_ratio = $source_width / $source_height;
$desired_aspect_ratio = $desired_width / $desired_height;
if ($source_aspect_ratio > $desired_aspect_ratio) {
// Triggered when source image is wider
$temp_height = $desired_height;
$temp_width = (int) ( $desired_height * $source_aspect_ratio );
} else {
// Triggered otherwise (i.e. source image is similar or taller)
$temp_width = $desired_width;
$temp_height = (int) ( $desired_width / $source_aspect_ratio );
}
// Resize the image into a temporary GD image
$temp_gdim = imagecreatetruecolor($temp_width, $temp_height);
imagecopyresampled(
$temp_gdim,
$source_gdim,
0, 0,
0, 0,
$temp_width, $temp_height,
$source_width, $source_height
);
// Copy cropped region from temporary image into the desired GD image
$x0 = ( $temp_width - $desired_width ) / 2;
$y0 = ( $temp_height - $desired_height ) / 2;
$desired_gdim = imagecreatetruecolor($desired_width, $desired_height);
imagecopy(
$desired_gdim,
$temp_gdim,
0, 0,
$x0, $y0,
$desired_width, $desired_height
);
return $desired_gdim;
}
Try to use Primage class, like in example
You can not specify that in the header. There are 2 ways to go about it.
1 : in the image tag, specify the width attribute, however this will force the smaller images to scale up as well, so probably not the best course of action.
2 : Resize the image on the fly with GD library and send the resultant image instead of the original.
Edit:
For resizing you may look into this very simple to use image resize class.
http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth($maxWidth);
$image->save('picture2.jpg');
Now you can redirect to picture2.jpg or send the image content inline. Also if the image is used often, then check on top of the script, if your resized image exists, if it does send it otherwise continue to resize.

PHP crop image to fix width and height without losing dimension ratio

im looking to create thumbnails that has 100px by 100px dimension. i've seen many articles explaining the methods but most end up having the width!=height if the dimension ratio is to be kept.
for example, i have a 450px by 350px image. i would like to crop to 100px by 100px. if i were to keep the ratio, i would end up having 100px by 77px. this makes it ugly when im listing these images in a row and column. however, a image without dimension ratio will look terrible as well.
i've seen images from flickr and they look fantastic. for example:
thumbnail: http://farm1.static.flickr.com/23/32608803_29470dfeeb_s.jpg
medium size: http://farm1.static.flickr.com/23/32608803_29470dfeeb.jpg
large size: http://farm1.static.flickr.com/23/32608803_29470dfeeb_b.jpg
tks
This is done by only using a part of the image as the thumbnail which has a 1:1 aspect ratio (mostly the center of the image). If you look closely you can see it in the flickr thumbnail.
Because you have "crop" in your question, I'm not sure if you didn't already know this, but what do you want to know then?
To use cropping, here is an example:
//Your Image
$imgSrc = "image.jpg";
//getting the image dimensions
list($width, $height) = getimagesize($imgSrc);
//saving the image into memory (for manipulation with GD Library)
$myImage = imagecreatefromjpeg($imgSrc);
// calculating the part of the image to use for thumbnail
if ($width > $height) {
$y = 0;
$x = ($width - $height) / 2;
$smallestSide = $height;
} else {
$x = 0;
$y = ($height - $width) / 2;
$smallestSide = $width;
}
// copying the part into thumbnail
$thumbSize = 100;
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
//final output
header('Content-type: image/jpeg');
imagejpeg($thumb);
Crop image with square based on lesser width or height
public function croppThis($target_url) {
$this->jpegImgCrop($target_url);
}
$target_url - is Name of image.
public function jpegImgCrop($target_url) {//support
$image = imagecreatefromjpeg($target_url);
$filename = $target_url;
$width = imagesx($image);
$height = imagesy($image);
$image_type = imagetypes($image); //IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM
if($width==$height) {
$thumb_width = $width;
$thumb_height = $height;
} elseif($width<$height) {
$thumb_width = $width;
$thumb_height = $width;
} elseif($width>$height) {
$thumb_width = $height;
$thumb_height = $height;
} else {
$thumb_width = 150;
$thumb_height = 150;
}
$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);
}
You can use this code.
You need to pass source image path and thumbnail size in px, and optional destination path. if you pass it will save the image else the thumb will be shown.
Only jpg, jpeg and png are allowed.
function cropImage($sourcePath, $thumbSize, $destination = null) {
$parts = explode('.', $sourcePath);
$ext = $parts[count($parts) - 1];
if ($ext == 'jpg' || $ext == 'jpeg') {
$format = 'jpg';
} else {
$format = 'png';
}
if ($format == 'jpg') {
$sourceImage = imagecreatefromjpeg($sourcePath);
}
if ($format == 'png') {
$sourceImage = imagecreatefrompng($sourcePath);
}
list($srcWidth, $srcHeight) = getimagesize($sourcePath);
// calculating the part of the image to use for thumbnail
if ($srcWidth > $srcHeight) {
$y = 0;
$x = ($srcWidth - $srcHeight) / 2;
$smallestSide = $srcHeight;
} else {
$x = 0;
$y = ($srcHeight - $srcWidth) / 2;
$smallestSide = $srcWidth;
}
$destinationImage = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($destinationImage, $sourceImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
if ($destination == null) {
header('Content-Type: image/jpeg');
if ($format == 'jpg') {
imagejpeg($destinationImage, null, 100);
}
if ($format == 'png') {
imagejpeg($destinationImage);
}
if ($destination = null) {
}
} else {
if ($format == 'jpg') {
imagejpeg($destinationImage, $destination, 100);
}
if ($format == 'png') {
imagepng($destinationImage, $destination);
}
}
}
I like using GDLib to fiddle with images, it's fantastically easy to work with also. There are lots of blog posts and tutorials out there. I would recommend using a class for it or similar though, as taking care of all the variations in the image can be very time consuming.
To complete #SvenKoschnicke code, here is little tool to process other image formats:
$sourceProperties = getimagesize($imgSrc);
$width = $sourceProperties[0];
$height = $sourceProperties[1];
switch ($sourceProperties[2]) {
case IMAGETYPE_PNG:
$myImage = imagecreatefrompng($imgSrc);
break;
case IMAGETYPE_GIF:
$myImage = imagecreatefromgif($imgSrc);
break;
case IMAGETYPE_JPEG:
$myImage = imagecreatefromjpeg($imgSrc);
break;
}

Cropping image in PHP

I'd like crop an image in PHP and save the file. I know your supposed to use the GD library but i'm not sure how. Any ideas?
Thanks
You could use imagecopy to crop a required part of an image. The command goes like this:
imagecopy (
resource $dst_im - the image object ,
resource $src_im - destination image ,
int $dst_x - x coordinate in the destination image (use 0) ,
int $dst_y - y coordinate in the destination image (use 0) ,
int $src_x - x coordinate in the source image you want to crop ,
int $src_y - y coordinate in the source image you want to crop ,
int $src_w - crop width ,
int $src_h - crop height
)
Code from PHP.net - a 80x40 px image is cropped from a source image
<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);
// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
?>
This function will crop image maintaining image aspect ratio :)
function resize_image_crop($image, $width, $height)
{
$w = #imagesx($image); //current width
$h = #imagesy($image); //current height
if ((!$w) || (!$h)) { $GLOBALS['errors'][] = 'Image couldn\'t be resized because it wasn\'t a valid image.'; return false; }
if (($w == $width) && ($h == $height)) { return $image; } //no resizing needed
$ratio = $width / $w; //try max width first...
$new_w = $width;
$new_h = $h * $ratio;
if ($new_h < $height) { //if that created an image smaller than what we wanted, try the other way
$ratio = $height / $h;
$new_h = $height;
$new_w = $w * $ratio;
}
$image2 = imagecreatetruecolor ($new_w, $new_h);
imagecopyresampled($image2,$image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
if (($new_h != $height) || ($new_w != $width)) { //check to see if cropping needs to happen
$image3 = imagecreatetruecolor ($width, $height);
if ($new_h > $height) { //crop vertically
$extra = $new_h - $height;
$x = 0; //source x
$y = round($extra / 2); //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
} else {
$extra = $new_w - $width;
$x = round($extra / 2); //source x
$y = 0; //source y
imagecopyresampled($image3,$image2, 0, 0, $x, $y, $width, $height, $width, $height);
}
imagedestroy($image2);
return $image3;
} else {
return $image2;
}
}
To crop an image using GD you need to use a combination of GD methods, and if you look at "Example #1" on PHP's documentation of the imagecopyresampled method, it shows you how to crop and output an image, you would just need to add some code to that to capture and write the output to a file...
http://us2.php.net/manual/en/function.imagecopyresampled.php
There are also other options, including Image Magick which, if installed on your server, can be accessed directly using PHP's exec method (or similar) or you can install the PHP Imagick extension, which yields higher quality images and, in my opinion, is a little more intuitive and flexible to work with.
Finally, I've used the open source PHPThumb class library, which has a pretty simple interface and can work with multiple options depending on what's on your server, including ImageMagick and GD.
I use this script in some projects and it's pretty easy to use:
http://shiftingpixel.com/2008/03/03/smart-image-resizer/
The script requires PHP 5.1.0 (which is out since 2005-11-24 - time to upgrade if not yet at this version) and GD (which is rarely missing from good Web hosts).
Here is an example of it's use in your HTML:
<img src="/image.php/coffee-bean.jpg?width=200&height=200&image=/wp-content/uploads/2008/03/coffee-bean.jpg" alt="Coffee Bean" />
I just created this function and it works for my needs, creating a centered and cropped thumbnail image. It is streamlined and doesn't require multiple imagecopy calls like shown in webGautam's answer.
Provide the image path, the final width and height, and optionally the quality of the image. I made this for creating thumbnails, so all images are saved as JPGs, you can edit it to accommodate other image types if you require them. The main point here is the math and method of using imagecopyresampled to produce a thumbnail. Images are saved using the same name, plus the image size.
function resize_crop_image($image_path, $end_width, $end_height, $quality = '') {
if ($end_width < 1) $end_width = 100;
if ($end_height < 1) $end_height = 100;
if ($quality < 1 || $quality > 100) $quality = 60;
$image = false;
$dot = strrpos($image_path,'.');
$file = substr($image_path,0,$dot).'-'.$end_width.'x'.$end_height.'.jpg';
$ext = substr($image_path,$dot+1);
if ($ext == 'jpg' || $ext == 'jpeg') $image = #imagecreatefromjpeg($image_path);
elseif($ext == 'gif') $image = #imagecreatefromgif($image_path);
elseif($ext == 'png') $image = #imagecreatefrompng($image_path);
if ($image) {
$width = imagesx($image);
$height = imagesy($image);
$scale = max($end_width/$width, $end_height/$height);
$new_width = floor($scale*$width);
$new_height = floor($scale*$height);
$x = ($new_width != $end_width ? ($width - $end_width) / 2 : 0);
$y = ($new_height != $end_height ? ($height - $end_height) / 2 : 0);
$new_image = #imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image,$image,0,0,$x,$y,$new_width,$new_height,$width - $x,$height - $y);
imagedestroy($image);
imagejpeg($new_image,$file,$quality);
imagedestroy($new_image);
return $file;
}
return false;
}
You can use below method to crop image,
/*parameters are
$image =source image name
$width = target width
$height = height of image
$scale = scale of image*/
function resizeImage($image,$width,$height,$scale) {
//generate new image height and width of source image
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
//Create a new true color image
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
//Create a new image from file
$source = imagecreatefromjpeg($image);
//Copy and resize part of an image with resampling
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
//Output image to file
imagejpeg($newImage,$image,90);
//set rights on image file
chmod($image, 0777);
//return crop image
return $image;
}

Categories