【问题标题】:How to validate image aspect ratio before uploading in codeigniter如何在codeigniter中上传之前验证图像纵横比
【发布时间】:2016-03-01 07:05:56
【问题描述】:

我需要验证图像的纵横比 (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 ajax codeigniter


    【解决方案1】:

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

    【讨论】:

    • 根据您的代码,我需要先上传图片,然后我必须将上传的图片网址传递给oImg.src,然后它会给出尺寸。但是我想在选择图像时验证方面收音机,在将其上传到服务器之前会对其进行检查。
    • 真的 - 没有真正的好处 - 很抱歉在这种情况下误导了你。
    【解决方案2】:

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

    $config['maintain_ratio'] = TRUE;
    

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

    【讨论】:

    • 我想在上传图片之前验证宽高比。
    • 请在提交答案前仔细阅读问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2019-04-02
    • 2021-08-23
    • 2019-12-13
    • 2012-05-11
    • 2018-04-29
    相关资源
    最近更新 更多