Home > Blockchain >  How to compress an image with codeigniter image_lib?
How to compress an image with codeigniter image_lib?

Time:07-11

I am trying to compress size of the image in my codeigniter php website and wrote the following code in my controller:

$this->load->library('image_lib');
$this->load->library('upload');
$image = array();
$ImageCount = count($_FILES['pimage']['name']);
for($i = 0; $i < $ImageCount; $i  ){
    $_FILES['file']['name']       = $_FILES['pimage']['name'][$i];
    $_FILES['file']['type']       = $_FILES['pimage']['type'][$i];
    $_FILES['file']['tmp_name']   = $_FILES['pimage']['tmp_name'][$i];
    $_FILES['file']['error']      = $_FILES['pimage']['error'][$i];
    $_FILES['file']['size']       = $_FILES['pimage']['size'][$i];
    
    // File upload configuration
    $uploadPath = './uploads/products/';
    $config['image_library'] = 'gd2';
    
    $config['upload_path'] = $uploadPath;
    $config['allowed_types'] = 'jpg|jpeg|png|gif';
    $config['quality'] = '60%';
    
    // Load and initialize upload library
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    
    // Upload file to server
    if($this->upload->do_upload('file')){
        // Uploaded file data
        $imageData = $this->upload->data();
        // $uploadImgData[$i]['image_name'] = $imageData['file_name'];
        $uploadImgData[] = $imageData['file_name'];
    }
}

but after upload the image is still saved in the same size, can anyone please tell me what is wrong in here?

CodePudding user response:

You need to pair the config setting with a library action like resize (R), cropping (C), rotation (X) or watermark (W).

see Processing Methods

and Preferences:

Preference Default Value Options Description Availability
quality 90% 1 - 100% Sets the quality of the image. The higher the quality the larger the file size. R, C, X, W

At the moment you are just setting a bunch of config data and upload the image without a processing method, hence nothing is changed.

  • Related