无法通过php调整图像大小

时间:2016-11-20 21:44:20

标签: php

我在php中是noobie,只是创建图像大小调整脚本。 以下代码是关于我尝试做的事情。特别是 - 尝试了解如何在添加后调整图像大小,但面临一些问题。请帮帮我,我的代码出了什么问题?

        $temp = getimagesize($_FILES['file']['tmp_name']); 
        $name = '/upload/'.date('Ymd-His').'img'. rand(10000, 99999).'.jpg';

        if (!in_array($matches[1], $array2)) {
            $errors['file'] = 'Wrong file extension';
        } elseif (!in_array($temp['mime'], $array)) { 
            $errors['file'] = 'Wrong type of file';
        } elseif (!move_uploaded_file($_FILES['file']['tmp_name'],'.'.$name)){ 
            $errors['file'] = 'image is not loaded';
        } else {

           // there is a problem

            $tmp = imagecreatetruecolor(200, 150);    
            $image = imagecreatefromjpeg($name);      
            imagecopyresampled($tmp, $image, 0,0,0,0, 200, 150, $temp[0], $temp[1]);
            imagejpeg($tmp, 100);

     // which i can`t fix

        }

    } else {
        $errors['file'] = 'The file is not an image. Valid file types: jpg, png, gif';
    }
}
}

1 个答案:

答案 0 :(得分:0)

使用这些功能:

    #####  This function will proportionally resize image ##### 
    function do_resize_image($source, $destination, $image_type, $max_size, $image_width, $image_height, $quality){

        if($image_width <= 0 || $image_height <= 0){return false;} //return false if nothing to resize

        //do not resize if image is smaller than max size
        if($image_width <= $max_size && $image_height <= $max_size){
            if(save_image($source, $destination, $image_type, $quality)){
                return true;
            }
        }

        //Construct a proportional size of new image
        $image_scale    = min($max_size/$image_width, $max_size/$image_height);
        $new_width      = ceil($image_scale * $image_width);
        $new_height     = ceil($image_scale * $image_height);

        $new_canvas     = imagecreatetruecolor( $new_width, $new_height ); //Create a new true color image

        //Copy and resize part of an image with resampling
        if(imagecopyresampled($new_canvas, $source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height)){
            save_image($new_canvas, $destination, $image_type, $quality); //save resized image
        }

        return true;
    }

##### Saves image resource to file ##### 
function save_image($source, $destination, $image_type, $quality){
    switch(strtolower($image_type)){//determine mime type     
        case 'image/jpeg': case 'image/pjpeg': 
            imagejpeg($source, $destination, $quality); return true; //save jpeg file
            break;
        default: return false;
    }
}