I created a function for generating and saving multiple image sizes when a user uploads an image via a web form. I was wondering, how can I better optimize my code (reduce the number of lines while still being easily readable)
save_image($_FILES['image'], $_GET['member_id'], 250, 300, large) //usage example
The Function
function save_image($file, $id, $sizex, $sizey, $pre){
$image=$_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
if ($image){
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension == "jpg") || ($extension == "jpeg")){
$size = getimagesize($tmpName);
$max_x = 180;
$max_y = 300;
$img = imagecreatefromjpeg($file['tmp_name']);
$imagex = imagesx($img);
$imagey = imagesy($img);
$dim = max($imagex/$max_x, $imagey/$max_y);
$nx = $imagex/$dim;
$ny = $imagey/$dim;
$image = imagecreatetruecolor($nx, $ny);
imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey);
imagejpeg($image, '../images/uploads/'.$id.'-large.jpg');
//Make the thumb
$size = getimagesize($tmpName);
$max_x = 120;
$max_y = 230;
$img = imagecreatefromjpeg($file['tmp_name']);
$imagex = imagesx($img);
$imagey = imagesy($img);
$dim = max($imagex/$max_x, $imagey/$max_y);
$nx = $imagex/$dim;
$ny = $imagey/$dim;
$image = imagecreatetruecolor($nx, $ny);
imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey);
imagejpeg($image, '../images/uploads/'.$id.'-med.jpg');
$size = getimagesize($tmpName);
$max_x = 60;
$max_y = 115;
$img = imagecreatefromjpeg($file['tmp_name']);
$imagex = imagesx($img);
$imagey = imagesy($img);
$dim = max($imagex/$max_x, $imagey/$max_y);
$nx = $imagex/$dim;
$ny = $imagey/$dim;
$image = imagecreatetruecolor($nx, $ny);
imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey);
imagejpeg($image, '../images/uploads/'.$id.'-thumb.jpg');
}else{
return false;
}
}else{
return false;
}
return true;
}
First of all I noticed you create a variable and it has not been used.
$size = getimagesize($tmpName);
So why call a function and assign its value when it is not being used.
Secondly to get the width and height you don't have to do
$imagex = imagesx($img);
$imagey = imagesy($img);
So I would suggest you replace the 3 lines mentioned in this code with a single one
list($width, $height, $type, $attr) = getimagesize($tmpName);
Finally instead of duplicating the code create a function with parameters passed and call the function as it is shown in the comments above.
Also noticed that you send "large" i.e image size as the parameter then why are you running through the thumb and med cases. Would suggest use switch cases like change the save function to
function save_image($_FILES['image'], $_GET['member_id'], 250, 300, $type = "large")
and then use a switch on $type.
You have 3 times almost the same code
$size = getimagesize($tmpName);
$max_x = 60;
$max_y = 115;
$img = imagecreatefromjpeg($file['tmp_name']);
$imagex = imagesx($img);
$imagey = imagesy($img);
$dim = max($imagex/$max_x, $imagey/$max_y);
$nx = $imagex/$dim;
$ny = $imagey/$dim;
$image = imagecreatetruecolor($nx, $ny);
imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey);
imagejpeg($image, '../images/uploads/'.$id.'-thumb.jpg');
You should easily be able to make a function for that, that's a good start.
A lot of your code is redundant.
You could make a little function :
function repetitiveFunctionForPicture($image, $max_x, $max_y,$tmpName, $file){
$size = getimagesize($tmpName);
$img = imagecreatefromjpeg($file['tmp_name']);
$imagex = imagesx($img);
$imagey = imagesy($img);
$dim = max($imagex/$max_x, $imagey/$max_y);
$nx = $imagex/$dim;
$ny = $imagey/$dim;
$image = imagecreatetruecolor($nx, $ny);
imagecopyresampled($image, $img, 0, 0, 0, 0, $nx, $ny, $imagex, $imagey);
imagejpeg($image, '../images/uploads/'.$id.'-large.jpg');
}
which can be called like this :
repetitiveFunctionForPicture($image, 180, 300,$tmpName, $file);
Related
How can I set this code to return images in 1:1 (square)?
The purpose is to create a square (non stretched) thumbnail.
I've tried making changes in the 'if section'. I get a square image but stretched. I want it to be cropped.
define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);
$source_image_path = {here the source filename};
$thumbnail_image_path = {here de thumb filename};
list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
switch ($source_image_type) {
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif($source_image_path);
break;
case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg($source_image_path);
break;
case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng($source_image_path);
break;
}
$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
$thumbnail_image_width = $source_image_width;
$thumbnail_image_height = $source_image_height;
} elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
$thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
} else {
$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
}
$thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
PS. It's not a duplicate, I've read several questions of this topic, but I'm unable to integrate it whit my code.
This function did the trick
function crop_img($imgSrc){
//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 = min($width,$height);
$thumb = imagecreatetruecolor($thumbSize, $thumbSize);
imagecopyresampled($thumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);
unlink($imgSrc);
imagejpeg($thumb,$imgSrc);
#imagedestroy($myImage);
#imagedestroy($thumb);
}
Found in: PHP crop image to fix width and height without losing dimension ratio
Use this code this code uploads image to folder and renames the file and thumb will be created with same name
HTML
<INPUT NAME="userfile[]" TYPE="file">
image directory "upimg/"
thumb directory thimg
php processing
$rename = md5(rand() * time());
$add = "upimg/" . $rename . $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $add)) {
echo "Successfully uploaded the image";
chmod("$add", 0777);
} else {
exit;
}
$n_width = 200;
$n_height = 200;
$tsrc = "thimg/" . $rename . $_FILES['userfile']['name'];
if (!($_FILES['userfile']['type'] == "image/jpeg" OR $_FILES['userfile']['type'] == "image/gif")) {
exit;
}
if ($_FILES['userfile']['type'] == "image/gif") {
$im = ImageCreateFromGIF($add);
$width = ImageSx($im);
$height = ImageSy($im);
$newimage = imagecreatetruecolor($n_width, $n_height);
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
if (function_exists("imagegif")) {
Header("Content-type: image/gif");
ImageGIF($newimage, $tsrc);
} elseif (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage, $tsrc);
}
chmod("$tsrc", 0777);
}
if ($_FILES['userfile']['type'] == "image/jpeg") {
$im = ImageCreateFromJPEG($add);
$width = ImageSx($im);
$height = ImageSy($im);
$newimage = imagecreatetruecolor($n_width, $n_height);
imageCopyResized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
ImageJpeg($newimage, $tsrc);
chmod("$tsrc", 0777);
}
This question already has answers here:
Resize image in PHP
(13 answers)
Closed 6 years ago.
function resize($originalImage){
list($width, $height) = getimagesize($originalImage);
$newName=basename($originalImage);
$imageResized = imagecreatetruecolor(128, 128);
$imageTmp = imagecreatefromjpeg ($originalImage);
imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 128, 128, $width, $height);
imagejpeg($imageResized, "resizedImg/$newName",100);
imageDestroy($imageResized);
}
The script returns the image with the correct name but it's just black? Any ideas?
If you have trouble with image resizing use this code for it. Do the modifications as you need it.
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);
}
}
I want to resize an image PNG with transparence plz help. Here is the code :
function createThumb($upfile, $dstfile, $max_width, $max_height){
$size = getimagesize($upfile);
$width = $size[0];
$height = $size[1];
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
if( ($width <= $max_width) && ($height <= $max_height)) {
$tn_width = $width;
$tn_height = $height;
} elseif (($x_ratio * $height) < $max_height) {
$tn_height = ceil($x_ratio * $height);
$tn_width = $max_width;
} else {
$tn_width = ceil($y_ratio * $width);
$tn_height = $max_height;
}
if($size['mime'] == "image/jpeg"){
$src = ImageCreateFromJpeg($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
imageinterlace( $dst, true);
ImageJpeg($dst, $dstfile, 100);
} else if ($size['mime'] == "image/png"){
$src = ImageCreateFrompng($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
// integer representation of the color black (rgb: 0,0,0)
$background = imagecolorallocate($dst, 255, 255, 0);
// removing the black from the placeholder
imagecolortransparent($dst, $background);
// turning off alpha blending (to ensure alpha channel information
// is preserved, rather than removed (blending with the rest of the
// image in the form of black))
imagealphablending($dst, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($dst, true);
Imagepng($dst, $dstfile);
} else {
$src = ImageCreateFromGif($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
imagegif($dst, $dstfile);
}
}
The image source :
The current result (that I don't want) is :
How can I resize the image and maintain the transparency of the background color? Need help, please. Thanks.
imagecopyresampled is in the wrong place. This should be called after you have set the background colour:
$src = ImageCreateFrompng($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
// use imagecolorallocatealpha to set BG as transparent:
$background = imagecolorallocatealpha($dst, 255, 255, 255, 127);
// turning off alpha blending as it's not needed
imagealphablending($dst, false);
// turning on alpha channel information saving (to ensure the full range
// of transparency is preserved)
imagesavealpha($dst, true);
// Do this here!
imagecopyresampled($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height,$width, $height);
Imagepng($dst, $dstfile);
<?php
function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
if(file_exists($newname))
#unlink($newname);
if(!file_exists($name))
return false;
$arr = split("\.",$name);
$ext = $arr[count($arr)-1];
if($ext=="jpeg" || $ext=="jpg"){
$img = #imagecreatefromjpeg($name);
} elseif($ext=="png"){
$img = #imagecreatefrompng($name);
} elseif($ext=="gif") {
$img = #imagecreatefromgif($name);
}
if(!$img)
return false;
$old_x = imageSX($img);
$old_y = imageSY($img);
if($old_x < $new_w && $old_y < $new_h) {
$thumb_w = $old_x;
$thumb_h = $old_y;
} elseif ($old_x > $old_y) {
$thumb_w = $new_w;
$thumb_h = floor(($old_y*($new_h/$old_x)));
} elseif ($old_x < $old_y) {
$thumb_w = floor($old_x*($new_w/$old_y));
$thumb_h = $new_h;
} elseif ($old_x == $old_y) {
$thumb_w = $new_w;
$thumb_h = $new_h;
}
$thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
$thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
$new_img = ImageCreateTrueColor($thumb_w, $thumb_h);
if($transparency) {
if($ext=="png") {
imagealphablending($new_img, false);
$colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
imagefill($new_img, 0, 0, $colorTransparent);
imagesavealpha($new_img, true);
} elseif($ext=="gif") {
$trnprt_indx = imagecolortransparent($img);
if ($trnprt_indx >= 0) {
//its transparent
$trnprt_color = imagecolorsforindex($img, $trnprt_indx);
$trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
imagefill($new_img, 0, 0, $trnprt_indx);
imagecolortransparent($new_img, $trnprt_indx);
}
}
} else {
Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
}
imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
if($border) {
$black = imagecolorallocate($new_img, 0, 0, 0);
imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
}
if($base64) {
ob_start();
imagepng($new_img);
$img = ob_get_contents();
ob_end_clean();
$return = base64_encode($img);
} else {
if($ext=="jpeg" || $ext=="jpg"){
imagejpeg($new_img, $newname);
$return = true;
} elseif($ext=="png"){
imagepng($new_img, $newname);
$return = true;
} elseif($ext=="gif") {
imagegif($new_img, $newname);
$return = true;
}
}
imagedestroy($new_img);
imagedestroy($img);
return $return;
}
//example useage
createthumb("1.png", "2.png", 64,64,true, true, false);
?>
Hope this can help...
I dont deserve credit for this code... just found it op net... enjoy
I am using this function
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagesavealpha($new_image, true);
$trans_colour = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $trans_colour);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
What I want to do is make a square image. I would like to resize by the smallest attribute, then instead of the larger number being squished. I would like the edges chopped off.
So if I have an image which is 213 x 180 which I need resized to 150 x 150
I can resize the image to 150 height before it hits this function.
What I don't know how to do is take the width and chop off the edges to get 150 width without distortion.
Does anyone know how to do this?
By "Chop off" the edge i guess you mean making a crop of you're image, right ?
For croping a image you could use imagecopyresized.
A little example :
$imageSrc = //Your source image;
$tempImage = imagecreatetruecolor(150,150);
// CropStartX et cropStartY have to be computed to suit your needs
imagecopyresized($tempImage,$imageSrc,0,0,$cropStartX,$cropStartY,150,150,150,150);
// $tempImage now contain your cropped image.
This is copied from an old project of mine, does what you need:
static public function resizeCropAndMove($from_path, $to_path, $max_width, $max_height)
{
$image_info = getImageSize($from_path);
switch ($image_info['mime']) {
case 'image/jpeg': $input = imageCreateFromJPEG($from_path); break;
default:
return false;
}
$input_width = imagesx($input);
$input_height = imagesy($input);
$output = imageCreateTrueColor($max_width, $max_height);
if ($input_width <= $input_height) { //portrait
$lamda = $max_width / $input_width;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$top = (int)round(($temp_height - $max_height) / 2);
$left = 0;
}
} else { //landscape
$lamda = $max_height / $input_height;
if ($lamda < 1) {
$temp_width = (int)round($lamda * $input_width);
$temp_height = (int)round($lamda * $input_height);
$temp = imagecreatetruecolor($temp_width, $temp_height);
imageCopyResampled($temp, $input, 0, 0, 0, 0, $temp_width, $temp_height, $input_width, $input_height);
$left = (int)round(($temp_width - $max_width) / 2);
$top = 0;
}
}
if ($lamda < 1) {
imageCopyResampled($output, $temp, 0, 0, $left, $top, $max_width, $max_height, $max_width, $max_height);
imagePNG($output, $to_path);
imagedestroy($temp);
} else {
imagePNG($input, $to_path);
}
imageDestroy($input);
imageDestroy($output);
}
function createCroppedThumb($thumbSourcePath, $thumbSavePath, $thumbDim){
// Get dimensions of the original image
$detail = getimagesize($thumbSourcePath);
$current_width = $detail[0];
$current_height = $detail[1];
$imageType = $detail[2];
// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 0;
$top = 0;
// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = $thumbDim;
$crop_height = $thumbDim;
// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
switch($imageType){
case '1':
$current_image = imagecreatefromgif($thumbSourcePath);
break;
case '2':
$current_image = imagecreatefromjpeg($thumbSourcePath);
break;
case '3':
$current_image = imagecreatefrompng($thumbSourcePath);
break;
default:
throw new Exception('unknown image type');
break;
}
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
switch($imageType){
case '1':
imagegif($canvas,$thumbSavePath,100);
break;
case '2':
imagejpeg($canvas,$thumbSavePath,100);
break;
case '3':
imagepng($canvas,$thumbSavePath,100);
break;
default:
throw new Exception('unknown image type');
break;
}
}
I'm using PHP to generate thumbnails. The problem is that I have a set width and height the thumbnails need to be and often times the images are stretched.
What I'd like is the image to remain at the same proportions and just have black filler (or any color) either on the left & right for tall images or top & bottom for wide images.
Here is the code I'm currently using: (dumbed down a bit for readability)
$temp_image_file = imagecreatefromjpeg("http://www.example.com/image.jpg");
list($width,$height) = getimagesize("http://www.example.com/image.jpg");
$image_file = imagecreatetruecolor(166,103);
imagecopyresampled($image_file,$temp_image_file,0,0,0,0,166,103,$width,$height);
imagejpeg($image_file,"thumbnails/thumbnail.jpg",50);
imagedestroy($temp_image_file);
imagedestroy($image_file);
You'll need to calculate the new width & height to keep the image proportionat. Check out example 2 on this page:
http://us3.php.net/imagecopyresampled
Okay got it working, here's what I ended up doing:
$filename = "http://www.example.com/image.jpg";
list($width,$height) = getimagesize($filename);
$width_ratio = 166 / $width;
if ($height * $width_ratio <= 103)
{
$adjusted_width = 166;
$adjusted_height = $height * $width_ratio;
}
else
{
$height_ratio = 103 / $height;
$adjusted_width = $width * $height_ratio;
$adjusted_height = 103;
}
$image_p = imagecreatetruecolor(166,103);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width) / 2),ceil((103 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);
imagejpeg($image_p,"thumbnails/thumbnail.jpg",50);
Here's a function I wrote that takes a GD image object, max width, max height, and rescales within those parameters:
function resized($im, $mx, $my) {
$x = $nx = imagesx($im);
$y = $ny = imagesy($im);
$ar = $x / $y;
while ($nx > $mx || $ny > $my) {
if ($nx > $mx) {
$nx = $mx;
$ny = $nx / $ar;
}
if ($ny > $my) {
$ny = $my;
$nx = $ny * $ar;
}
}
if ($nx != $x) {
$im2 = imagecreatetruecolor($nx, $ny);
imagecopyresampled($im2, $im, 0, 0, 0, 0, $nx, $ny, $x, $y);
return $im2;
} else {
return $im;
}
}
If the resulting image doesn't need rescaling then it just returns the original image.
Have a look at this upload class. It does what you want and a lot more besides.
This rescales the image to the larger size of the width and height and then crops it to the correct size.
// Crete an image forced to width and height
function createFixedImage($img, $id=0, $preFix=false, $mw='100', $mh='100', $quality=90){
// Fix path
$filename = '../'.$img;
// Check for file
if(file_exists($filename))
{
// Set a maximum height and width
$width = $mw;
$height = $mh;
// 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($mw, $mh);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, "../images/stories/catalog/{$preFix}{$id}.jpg", $quality);
}
}