CodeIgniter上传图像然后调整大小

时间:2012-04-05 10:41:40

标签: php codeigniter codeigniter-2

我正在尝试上传图片并调整大小,到目前为止,上传工作正在进行,并且还创建了缩略图图像。但我不能让原始图像调整大小。所有发生的事情是文件以原始大小直接上传到文件夹。我想我正在尝试将此图像调整大小,然后覆盖最初上传的文件。

这是我的代码,我错过了什么:

//Initialise the upload file class
    $config['upload_path'] = './image_uploads/';
    $config['allowed_types'] = 'jpg|jpeg|gif|png';
    $config['max_size'] = '6048';
    $this->load->library('upload', $config);

    $userfile = "_upload_image";
            //check if a file is being uploaded
            if(strlen($_FILES["_upload_image"]["name"])>0){

                if ( !$this->upload->do_upload($userfile))//Check if upload is unsuccessful
                {
                    $upload_errors = $this->upload->display_errors('', '');
                    $this->session->set_flashdata('errors', 'Error: '.$upload_errors);   
                    redirect('admin/view_food/'.$food->course_id);  
                }
                else
                {
                    //$image_data = $this->upload->data();

                     ////[ THUMB IMAGE ]
                    $config2['image_library'] = 'gd2';
                    $config2['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                    $config2['new_image'] = './image_uploads/thumbs';
                    $config2['maintain_ratio'] = TRUE;
                    $config2['create_thumb'] = TRUE;
                    $config2['thumb_marker'] = '_thumb';
                    $config2['width'] = 75;
                    $config2['height'] = 50;
                    $this->load->library('image_lib',$config2); 

                    if ( !$this->image_lib->resize()){
                $this->session->set_flashdata('errors', $this->image_lib->display_errors('', ''));   
              }

                    //[ MAIN IMAGE ]
                    $config['image_library'] = 'gd2';
                    $config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                    //$config['new_image'] = './image_uploads/';
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 250;
                    $config['height'] = 250;
                    $this->load->library('image_lib',$config); 

                    if ( !$this->image_lib->resize()){
                $this->session->set_flashdata('errors', $this->image_lib->display_errors('', ''));   
              }
               }      
           }  

3 个答案:

答案 0 :(得分:4)

您是否尝试将此添加到配置选项

$config['overwrite'] = TRUE;

这应该可以解决问题。

根据文件

  

如果设置为true,如果存在与您要上载的文件同名的文件,则会覆盖该文件。如果设置为false,如果存在另一个具有>同名的文件,则会将数字附加到文件名。

答案 1 :(得分:4)

我一直在尝试创建过去20小时的缩略图,直到我意识到我在搞乱代码的时候我没有成功,我没有初始化我的配置阵列!!!

加载 image_lib

后,只需添加以下代码
$this->image_lib->initialize($config);

希望这对你有用...........竖起大拇指!

答案 2 :(得分:0)

如果您喜欢使用带有CI的Image,我强烈推荐使用image_moo库。