如何调整上传时多个图像文件的大小?

时间:2018-07-13 02:50:58

标签: php codeigniter

我有以下php代码可以上传:

$data = array();
$filesCount = count($_FILES['img']['name']);
for($i = 0; $i < $filesCount; $i++)
{
    $_FILES['userFile']['name'] = $_FILES['img']['name'][$i];
    $_FILES['userFile']['type'] = $_FILES['img']['type'][$i];
    $_FILES['userFile']['tmp_name'] = $_FILES['img']['tmp_name'][$i];
    $_FILES['userFile']['error'] = $_FILES['img']['error'][$i];
    $_FILES['userFile']['size'] = $_FILES['img']['size'][$i];


    $id = $this->session->userdata('ses_id');
    $tabel = $this->session->userdata('ses_tabel');
    if (!file_exists('uploads/'.$tabel.'/kategori'))
    {
        mkdir('uploads/'.$tabel.'/kategori', 0777, true);
    }else{  
        $uploadPath = 'uploads/'.$tabel.'/kategori';
        $newname = $idkategori.'_'.$nama;
        $config['upload_path'] = $uploadPath;
        $config['allowed_types'] = 'jpg|png|jpeg';
        $config['file_name'] = $newname;

        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        if($this->upload->do_upload('userFile')){
            $fileData = $this->upload->data();
            $cfg['image_library'] = 'gd2';
            $cfg['quality'] = '50%';
            $this->load->library('image_lib');
            $this->image_lib->initialize($cfg);
            $this->image_lib->resize();
            $uploadData[$i]['nama'] = $this->input->post('nama_kategori');
            $uploadData[$i]['file_name'] = $fileData['file_name'];
            $uploadData[$i]['created'] = date("Y-m-d H:i:s");
            $uploadData[$i]['modified'] = date("Y-m-d H:i:s");
            $uploadData[$i]['id_resto'] = $id;
            $uploadData[$i]['id_kategori'] = $idkategori;
        }
    }
}

我的文件已上传但未调整大小,我想调整图像大小,以便在Android设备上请求图像时不会太大。 如有可能,请帮助我调整宽度和高度的大小。

对不起,英语不好, 谢谢。

3 个答案:

答案 0 :(得分:0)

此函数使用PHP的GD库,并在调整图像大小的同时保持原始图像的适当长宽比。您也可以裁剪图像,以便裁剪并填充所需尺寸的空间。只需进行一些设置即可。

function scaleMyImage($filePath, $newPath, $newSize, $crop = NULL){

  $img = imagecreatefromstring(file_get_contents($filePath));

  $dst_x = 0;
  $dst_y = 0;

  $width   = imagesx($img);
  $height  = imagesy($img);

  $newWidth   = $newSize;
  $newHeight  = $newSize;

  $aspectRatio = $width/$height;

  if($width < $height){  //Portrait.

    if($crop){

      $newWidth   = floor($width * ($newSize / $width));
      $newHeight  = floor($height * ($newSize / $width));
      $dst_y = (floor(($newHeight - $newSize)/2)) * -1;

    }else{

      $newWidth = floor($width * ($newSize / $height));
      $newHeight = $newSize;
      $dst_x = floor(($newSize - $newWidth)/2);

      }


  } elseif($width > $height) {  //Landscape


    if($crop){

      $newWidth   = floor($width * ($newSize / $height));
      $newHeight  = floor($height * ($newSize / $height));
      $dst_x = (floor(($newWidth - $newSize)/2)) * -1;


    }else{

      $newWidth = $newSize;
      $newHeight = floor($height * ($newSize / $width));
      $dst_y = floor(($newSize - $newHeight)/2);

      }


    }

  $finalImage = imagecreatetruecolor($newSize, $newSize);
  imagecopyresampled($finalImage, $img, $dst_x, $dst_y, 0, 0, $newWidth, $newHeight, $width, $height);

  //header('Content-Type: image/jpeg'); //<--Comment our if you want to save to file.
  imagejpeg($finalImage, $newPath, 60); //<--3rd param is quality.  60 does good job.  You can play around.

  imagedestroy($img);
  imagedestroy($finalImage);

}

$filePath = 'path/to/image.jpg';
$newPath = NULL; //Set to NULL to output to browser, otherwise provide a  filepath to save.
$newSize = 400; //Pixels
$crop = 1;  //Set to NULL if you don't want to crop.

scaleMyImage($filePath, $newPath, $newSize, $crop);

答案 1 :(得分:0)

您需要为镜像库配置设置新上传的镜像的路径。

了解更多here

    $this->upload->initialize($config, true);  // important 2nd param
    if ($this->upload->do_upload('userFile')) {
        $fileData = $this->upload->data();
        $cfg['source_image'] = $fileData['full_path'];
        list($width, $height) = getimagesize($fileData['full_path']);
        $cfg['width'] = $width - 1;
        $cfg['height'] = $height - 1;
        $cfg['image_library'] = 'gd2';
        $cfg['quality'] = '50%';
        $this->load->library('image_lib');
        $this->image_lib->initialize($cfg);
        if (!$this->image_lib->resize()) {
            log_message('error', 'resize failed: ' . $this->image_lib->display_errors());
        }
        $this->image_lib->clear();
        $uploadData[$i]['nama'] = $this->input->post('nama_kategori');
        $uploadData[$i]['file_name'] = $fileData['file_name'];
        $uploadData[$i]['created'] = date("Y-m-d H:i:s");
        $uploadData[$i]['modified'] = date("Y-m-d H:i:s");
        $uploadData[$i]['id_resto'] = $id;
        $uploadData[$i]['id_kategori'] = $idkategori;
    }

更新:

如果只想更改质量:

所以我忘了我之前已经回答过这类问题。如果深入研究图像库代码,您会注意到,仅当实际需要调整大小时才使用quality变量! CI会检查图像尺寸是否匹配指定的输出尺寸,是否匹配,或者是否在配置中未指定图像宽度和高度,它只会继续前进...因此质量不会受到影响。要对此进行 hack ,您可以获取宽度和高度并减去1px。我不会称它为漏洞,而更多是疏忽。

我个人不喜欢CI的上载或图像库,而是使用https://github.com/verot/class.upload.php(那里的问题不是问题)。

在这里,我想出了所有答案:Image compress in Codeigniter3

答案 2 :(得分:0)

兄弟,请尝试使用此代码来调整图片大小

 $fileData = $this->upload->data();

                            $configer =  array(
                                         'image_library'   => 'gd2',
                                          'source_image'    =>  $fileData['full_path'],
                                          'maintain_ratio'  =>  TRUE,
                                          'quality' => '40%' );

                                $this->image_lib->clear();
                                $this->image_lib->initialize($configer);
                                $this->image_lib->resize();