当我们上传时,如何在 Codeigniter 中减小图像的文件大小(以 KB 为单位)


how to reduce the file size in kb of an image in codeigniter when we upload?

我有一个页面,用户可以在其中拖放多个图像。我需要调整大小并将其存储为缩略图,并且还必须在不丢失图像宽度和高度的情况下减少以 kb 为单位的大图像。在编码点火器中最好的方法是什么?

     if ($_FILES["file"]["name"])
        {
        $targetPath = APPPATH . 'uploads/portfolios/';
        $result = $this->do_upload("file", $targetPath);
        $data =  array();
        if (!$result['status']) {
                $data['error_msg'] ="Can not upload Image for " . $result['error'] . " ";
        }
                else {
    $this->resize_image($targetPath . $result['upload_data']['file_name'],$targetPath,'120','120');

    $file_name = $result['upload_data']['raw_name'].'_thumb'.$result['upload_data']['file_ext'];    

        }
function resize_image($sourcePath, $desPath, $width = '500', $height = '500')
{
    $this->load->library('image_lib');
    $this->image_lib->clear();
    $config['image_library'] = 'gd2';
    $config['source_image'] = $sourcePath;
    $config['new_image'] = $desPath;
    //$config['quality'] = '100%';
    $config['create_thumb'] = TRUE;
    $config['maintain_ratio'] = false;
    $config['thumb_marker'] = '_thumb';
    $config['width'] = 120;
    $config['height'] = 120;
 $this->image_lib->initialize($config);
    if ($this->image_lib->resize())
        return true;
    return false;
}
  function do_upload($htmlFieldName, $path)
{
    $config['file_name'] = time();
    $config['upload_path'] = $path;
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = '20000';
    //$config['max_width'] = '2000';
    //$config['max_height'] = '2000';
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    unset($config);
    if (!$this->upload->do_upload($htmlFieldName))
    {
        return array('error' => $this->upload->display_errors(), 'status' => 0);
    } else
    {
        return array('status' => 1, 'upload_data' => $this->upload->data());
    }
}

我有类似的问题,可以通过本机php函数解决。

感谢他原来的答案中的 pez-cuckow。从它的问题也有改进,但它删除了对 gif 图像的支持。

function compressImage($source_url, $destination_url, $quality) {
  $info = getimagesize($source_url);
  if ($info['mime'] == 'image/jpeg') 
    $image= imagecreatefromjpeg($source_url);
  elseif ($info['mime'] == 'image/gif')
    $image = imagecreatefromgif($source_url);
  elseif ($info['mime'] == 'image/png')
    $image = imagecreatefrompng($source_url);
  //save file
  imagejpeg($image, $destination_url, $quality);
  //return destination file
  return $destination_url;
}