如何在codeigniter上传之前验证图像宽高比

时间:2016-03-01 07:05:57

标签: php ajax codeigniter

如果Codeigniter中的宽度(800)和高度(600),我需要验证宽高比(4:3)的图像。

这是我的代码:

public function uploadImage() {
        $upload_dir = './media/data/';
        $config['upload_path'] = $upload_dir . "800x600";
        $config['allowed_types'] = 'jpeg|jpg|png|gif|PNG';
        $config['max_size'] = '0';
        $config['max_width'] = '800';
        $config['min_width'] = '800';
        $config['max_height'] = '600';
        $config['min_height'] = '600';
        $name = time() . '_' . rand(00000000, 99999999);
        $config['file_name'] = $name;
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('image')) {
            $error = array('error' => $this->upload->display_errors());
            echo json_encode($error);
        } else {
            $data = array('upload_data' => $this->upload->data());
            $file = $data['upload_data']['full_path'];
            $this->ImageResize($file, $upload_dir, $name, $data['upload_data']['file_ext']);
            echo json_encode($data);
        }
    }

2 个答案:

答案 0 :(得分:2)

PHP在上传之前无法帮助获取图片尺寸,但您可以使用javascript加载图片并在上传之前推断尺寸。

var oImg=new Image();
oImg.src='https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/9/24/1411574454561/03085543-87de-47ab-a4eb-58e7e39d022e-620x372.jpeg'
oImg.onload=function(){
    alert('width:'+oImg.width+' height:'+oImg.height +' ratio:'+(oImg.width/oImg.height));
};

第二次尝试 - 不涉及远程图像,所以应该没问题

/* where imgx is the ID of the file input field */
document.getElementById('imgx').onchange=function(event){
    var oImg=new Image();
    for( i=0; i < this.files.length; i++ ){
        oImg.src=URL.createObjectURL( this.files[i] );
        oImg.onload=function(){
            var width=oImg.naturalWidth;
            var height=oImg.naturalHeight;

            alert('width:'+oImg.width+' height:'+oImg.height +' ratio:'+(oImg.width/oImg.height));
        };
    }
};

答案 1 :(得分:0)

此代码不起作用;它是上传图像的基本代码 如果您想在裁剪期间重新调整大小,则可以使用:

$config['maintain_ratio'] = TRUE;

但不能使用您的代码。您可以在上传代码之前检查验证。