Search code examples
phpcodeigniterimage-processingimage-resizing

Codeigniter resizing of image not working


I am trying to resize the uploaded image to height of 163px maintaining aspect ratio and then upload it to a folder. I tried with the following code:

$id=1;     // user id
$this->load->library('image_lib');
$filename=$_FILES['file']['name'];
$config['image_library'] = 'gd2';
$config['upload_path'] = './userdata/'.$id;
$config['height'] = '163px';
$config['maintain_ratio'] = TRUE;
//$config['master_dim'] = 'height';
$config['source_image'] = $filename;
$this->load->library('upload', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
if(!$this->upload->do_upload('file')) 
{               
     echo $this->data['error'] = $this->upload->display_errors();
}

However this is uploading the image to the correct folder but the image is not resized. I uploaded an image of size *170*128* and it is uploaded to folder as it is without resizing. What is wrong with my code?

Can anyone help me to find the problem?

Thanks in advance.


Solution

  • Try this cleaner version, the config for height or width doesn't need a px, hence your code is a little bit confusing :

    $id = 1;
    
    $config = array(
        'upload_path'   => './userdata/'.$id,
        'allowed_types' => 'gif|jpg|jpeg|png',
        'encrypt_name'  => true,
    );
    
    $this->load->library('upload', $config);
    
    $field_name = "file"; // change this with your file upload part's field name if different
    
    if ($this->upload->do_upload($field_name)) {
        $image = $this->upload->data();
        $config = array(
            'image_library'   => 'gd2',
            'source_image' => $image['full_path'],
            'maintain_ratio'  => true,
            'height'  => 163,
         );
         $this->load->library('image_lib', $config);
         if (!$this->image_lib->resize()) {
                echo $this->image_lib->display_errors();
         }
         $this->image_lib->clear();
    }