PHP resize image

Hi Guys!

I have created a function which resizes images. The function below works fine. However, I need the images to be an exact size. So each image uploaded using this function, should have an exact size of 100x100.

Is this possible, if so, how can I adapt the code below?


function CreateThumb($img_name,$filename,$image_type,$new_w,$new_h){
		// Image extension
		$ext = str_replace('image/','',$image_type);
		// Creates the new image using the appropriate function from gd library
		if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)){
			$src_img = imagecreatefromjpeg($img_name);
		}
		if(!strcmp("png",$ext)){
			$src_img = imagecreatefrompng($img_name);
		}
		if(!strcmp("gif",$ext)){
			$src_img = imagecreatefromgif($img_name);
		}
		// Gets the dimmensions of the image
		$old_x = imagesx($src_img);
		$old_y = imagesy($src_img);
		
		$ratio1 = $old_x/$new_w;
		$ratio2 = $old_y/$new_h;
		if($ratio1 > $ratio2) {
			$thumb_w = $new_w;
			$thumb_h = $old_y/$ratio1;
		}
		else {
			$thumb_h = $new_h;
			$thumb_w = $old_x/$ratio2;
		}
		
		// We create a new image with the new dimmensions
		$dst_img = imagecreatetruecolor($thumb_w,$thumb_h);
		
		// resize the big image to the new created one
		imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
		
		// Output the created image to the file. Now we will have the thumbnail into the file named by $filename
		if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext)){
			imagejpeg($dst_img,$filename);
		}
		if(!strcmp("png",$ext)){
			imagepng($dst_img,$filename);
		}
		if(!strcmp("gif",$ext)){
			imagegif($dst_img,$filename);
		}
		
		// Destroys source and destination images
		imagedestroy($dst_img);
		imagedestroy($src_img);
	}

I forgot that you need to resort the canvas with +repage.


$cmd = "convert input_image -thumbnail 100x100^ -gravity center -crop 100x100+0+0 +repage -quality 100";
exec("convert $cmd output_image"); 

if its not for an eCommerce website my class file would be pointless… you can use the one SpikeZ just pointed out.

Would you be willing to sell the class to me :slight_smile:

…or you could just register on phpclasses.org and use one of the submitted classes on there.
Example:
http://www.phpclasses.org/package/4879-PHP-Resize-images-of-different-formats.html

ImageResize.inc.php


<?php 
/** 
 * @author Dodit Suprianto 
 * Email: d0dit@yahoo.com 
 * Website: http://doditsuprianto.com 
 *  
 * Nama file: ImageResize.inc 
 *  
 * This class to resize an image from bigger to smaller size. 
 * Supporting PNG, JPG, and GIF image format. 
 *  
 * if you chose $proportional=true, it means that width or height image is proportional, example: 
 * $r = new Resize("test.jpg", 0, 500, true); height image will be 500 pixel and width will be proportional 
 * $r = new Resize("test.jpg", 500, 0, true); width image will be 500 pixel and height will be proportional 
 *  
 * if you chose $proportional=false, it means the width and height image will be customizable, example: 
 * $r = new Resize("test.jpg", 500, 500, true); it forces the image size will be 500 pixel width and 500 pixel height 
 *  
 */ 

    class Resize 
    { 
        private $file_source;         
        private $width_resize; 
        private $height_resize;     
        private $proportional; 
         
        public function __construct($file_source, $width_resize, $height_resize, $proportional) 
        { 
            $this->file_source = $file_source; 
            $this->width_resize = $width_resize; 
            $this->height_resize = $height_resize;             
            $this->proportional = $proportional; 
        } 
         
        public function setProportional($proportional) 
        { 
            $this->proportional = $proportional; 
        } 
         
        public function setFileSource($file_source) 
        { 
            $this->file_source = $file_source; 
        } 
         
        public function setHeightResize($height_resize) 
        { 
            $this->height_resize = $height_resize; 
        } 
         
        public function setWidthResize($width_resize) 
        { 
            $this->width_resize = $width_resize; 
        } 
         
        private function MemoryUsage() 
        { 
            $imageInfo    = getimagesize($this->file_source); 
            $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
               
            $memoryLimit = (int) ini_get('memory_limit')*1048576; 
            if ((memory_get_usage() + $memoryNeeded) > $memoryLimit) 
            ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M'); 
        } 
                 
        public function ImageResize() 
        { 
            $this->MemoryUsage(); 
            if ( $this->height_resize <= 0 && $this->width_resize <= 0 ) return false; 
        
            $info = getimagesize($this->file_source); 
            $image = ''; 
               
            $final_width = 0; 
            $final_height = 0; 
            list($width_old, $height_old) = $info; 
               
            if ($this->proportional)  
            {                   
                $proportion = $width_old / $height_old; 
                   
                if ( $this->width_resize > $this->height_resize && $this->height_resize != 0)  
                { 
                    $final_height = $this->height_resize; 
                    $final_width = $final_height * $proportion; 
                } 
                elseif ( $this->width_resize < $this->height_resize && $this->width_resize != 0)  
                { 
                    $final_width = $this->width_resize; 
                    $final_height = $final_width / $proportion; 
                } 
                elseif ( $this->width_resize == 0 )  
                { 
                    $final_height = $this->height_resize; 
                    $final_width = $final_height * $proportion;            
                } 
                elseif ( $this->height_resize == 0)  
                { 
                    $final_width = $this->width_resize; 
                    $final_height = $final_width / $proportion;            
                } 
                else  
                { 
                    $final_width = $this->width_resize; 
                    $final_height = $this->height_resize; 
                } 
            } 
            else  
            { 
                $final_width = ($this->width_resize <= 0) ? $this->width_resize_old : $this->width_resize; 
                $final_height = ($this->height_resize <= 0) ? $this->height_resize_old : $this->height_resize; 
            } 
           
            switch ( $info[2] )  
            { 
                case IMAGETYPE_GIF: 
                    $image = imagecreatefromgif($this->file_source); 
                break; 
                case IMAGETYPE_JPEG: 
                    $image = imagecreatefromjpeg($this->file_source); 
                break; 
                case IMAGETYPE_PNG: 
                    $image = imagecreatefrompng($this->file_source); 
                break; 
                default: 
                    return false; 
            } 
               
            $image_resized = imagecreatetruecolor( $final_width, $final_height ); 
            imagecolortransparent($image_resized, imagecolorallocate($image_resized, 0, 0, 0) ); 
            imagealphablending($image_resized, false); 
            imagesavealpha($image_resized, true); 
                              
            imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old); 
                             
            switch ( $info[2] )  
            { 
                case IMAGETYPE_GIF:                     
                    imagegif($image_resized, time().".gif", 100); 
                break; 
                case IMAGETYPE_JPEG: 
                    imagejpeg($image_resized, time().".jpg", 100); 
                break; 
                case IMAGETYPE_PNG: 
                    imagepng($image_resized, time().".png", 100); 
                break; 
                default: 
                    return false; 
            }               
            return true;     
        } 
    } 
?>

form


<html> 

<head> 
<title>Image Resize</title> 
</head> 

<body> 

<form enctype="multipart/form-data" method="POST" action="<?php echo $_SERVER['SELF'];?>"> 
    Photo: <input type=file name=photo size="20"><br> 
    Proportional: <input type="radio" value="yes" checked name="R1"> <input type="radio" value="no" name="R1"><br>
    Width: <input type="text" name="width" size="20"><br> 
    Height: <input type="text" name="height" size="20"><br> 
    <input type="submit" name="submit" value="Resize"> 
</form> 

<?php 
    if ($_POST['submit']) 
    { 
        require_once("ImageResize.inc.php"); 
                 
        if ($_POST['R1'] == "yes") 
        { 
            // proportional 
            $r = new Resize($_FILES['photo']['tmp_name'], $_POST['width'], 0, true); 
            // or $r = new Resize($_FILE['photo']['tmp_name'], 0, $_POST['height'], true); 
        } else 
        { 
            // Force the image size 
            $r = new Resize($_FILES[photo][tmp_name], $_POST[width], $_POST[height], false);             
        }         
        $r->ImageResize(); 
    } 
?> 

</body> 

</html>

your going to need alot more than that function

What you need to do is grab the original image strip the white space from around the image if you’re doing product images… if not then whatever. After you get the image you need to resize height… check if width =< 100 if not then resize based on width put that the image into a white canvas 100x100 or 250 x 250 or 500x500 etc… whatever you need

and walla. a perfectly sized image. :slight_smile: that’s going to be about 800 lines of code 2 class files and 5 functions; alot of coffee and big headache.

i made one about 3 yrs ago… still use it to this day for eCommerce sites.

I want the image to be good quality, but let’s say the image was 500 x 260 as you suggested then the image I guess will get cropped somehow. Whatever the scenario the outcome should be a 100 x 100 image.

Thanks in advance.

If you can use imagemagick it can be as easy as:


$cmd = "convert input_image -thumbnail 100x100^ -gravity center -crop 100x100+0+0 -quality 100";
exec("convert $cmd output_image");

Depending on your setup over 100 file types read and write without needing to specify different code options for each type.

you want to stretch the image to 100x100 what if an image is 250 x 560 ?