如何在编码点火器中上传之前验证图像纵横比


How to validate image aspect ratio before uploading in codeigniter

我需要验证图像的纵横比 (4:3),而不是在 Codeigniter 中的宽度 (800) 和高度 (600)。

这是我的代码:

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);
        }
    }
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));
        };
    }
};

此代码将不起作用;这是上传图像的基本代码。
如果要在裁剪过程中重新调整大小,则可以使用:

$config['maintain_ratio'] = TRUE;

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