02 January, 2011

php aspect ratio resizephp aspect ratio resize

<?php
class resize_image {
    public $max_width_or_height;
    
    public function display_image($image_dir){
        $image_dir = urlencode($image_dir);
        if(!file_exists($image_dir)) return 'File '.$image_dir.' does not exist!';
        $image_meta = getimagesize($image_dir);
        $image_width = $image_meta[0];
        $image_height = $image_meta[1];
        
        if(!is_numeric($this->max_width_or_height)) return 'Insert maximum size of new image!';
        if($image_width == $image_height){
            $new_image_width = $this->max_width_or_height;
            $new_image_height = $this->max_width_or_height;
        }
        elseif($image_width > $image_height){
            $new_image_width = $this->max_width_or_height;
            $new_image_height = $image_height / ($image_width / $this->max_width_or_height);
        }
        else{
            $new_image_width = $image_width / ($image_height / $this->max_width_or_height);
            $new_image_height = $this->max_width_or_height;
        }
        
        $type = substr(strrchr($image_meta['mime'], '/'), 1);
        if($type == 'jpeg'){
            $image_create_func = 'ImageCreateFromJPEG';
            $image_save_func = 'ImageJPEG';
            $new_image_ext = 'jpg';
        }
        elseif($type == 'png'){
            $image_create_func = 'ImageCreateFromPNG';
            $image_save_func = 'ImagePNG';
            $new_image_ext = 'png';
        }
        elseif($type == 'bmp'){
            $image_create_func = 'ImageCreateFromBMP';
            $image_save_func = 'ImageBMP';
            $new_image_ext = 'bmp';
        }
        elseif($type == 'gif'){
            $image_create_func = 'ImageCreateFromGIF';
            $image_save_func = 'ImageGIF';
            $new_image_ext = 'gif';
        }
        elseif($type == 'vnd.wap.wbmp'){
            $image_create_func = 'ImageCreateFromWBMP';
            $image_save_func = 'ImageWBMP';
            $new_image_ext = 'bmp';
        }
        elseif($type == 'xbm'){
            $image_create_func = 'ImageCreateFromXBM';
            $image_save_func = 'ImageXBM';
            $new_image_ext = 'xbm';
        }
        else{
            $image_create_func = 'ImageCreateFromJPEG';
            $image_save_func = 'ImageJPEG';
            $new_image_ext = 'jpg';
        }
        
        $image_identifier = ImageCreateTrueColor($new_image_width, $new_image_height);
        $new_image = $image_create_func($image_dir);
        ImageCopyResampled($image_identifier, $new_image, 0, 0, 0, 0, $new_image_width, $new_image_height, $image_width, $image_height);

        header('Content-Type: '.$image_meta['mime']);
        $image_save_func($image_identifier);
        echo $image_save_func($image_identifier, '');
    }
}

$image = new resize_image();
$image->max_width_or_height = '100';
$image->display_image('image location');

No comments:

Post a Comment