Tratar imágenes con Codeigniter utilizando las librerías "upload" e "image_lib", redimensionando dos veces la imagen subida.


Formulario HTML:

<form class="form-horizontal" id="form-img" name="form-img" action="" method="post" role="form" enctype="multipart/form-data">
<input type="file" id="my_image" name="my_image"/>
<button type="submit" name="updateprofileimg" id="updateprofileimg" class="btn btn-primary btn-default pull-right">Subir</button>
</form>

Código en el controlador:

$config['upload_path'] = './DIRECTORIO_DONDE_SUBIR_LA_IMG/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload("my_image")) {
     echo $this->upload->display_errors(); exit();
} else {     
     $data = array('upload_data' => $this->upload->data());
     $img_full_path = $config['upload_path'] . $data['upload_data']['file_name'];
     
     // REDIMENSIONAMOS
     $config['image_library'] = 'gd2';
     $config['source_image'] = $img_full_path;
     $config['maintain_ratio'] = TRUE;
     $config['width'] = 275;
     $config['height'] = 250;
     $config['new_image'] = './DIRECTORIO_IMG_REDIMENSIONADA1/'. $data['upload_data']['file_name'];
     $img_redim1 = $config['new_image'];
     $this->load->library('image_lib', $config);
     if (!$this->image_lib->resize()) {
          @unlink($img_full_path);
          echo $this->image_lib->display_errors(); exit();
     }
     $this->image_lib->clear();

     // REDIMENSIONAMOS DE NUEVO
     $config['image_library'] = 'gd2';
     $config['source_image'] = $img_full_path;
     $config['maintain_ratio'] = TRUE;
     $config['width'] = 75;
     $config['height'] = 50;
     $config['new_image'] = './DIRECTORIO_IMG_REDIMENSIONADA1/'. $data['upload_data']['file_name'];
     $this->image_lib->initialize($config); /// <<- IMPORTANTE
     if (!$this->image_lib->resize()) {
          @unlink($img_full_path);
          @unlink($img_redim1);
          echo $this->image_lib->display_errors(); exit();
     }
}

¿Preparado para empezar tu proyecto?

¡Comencemos!