2016-02-27 57 views
0

我有一個頁面,用戶將拖放多個圖像。我需要調整大小並將其存儲爲縮略圖,並且還必須減少kb中的大圖像,而不會丟失圖像的寬度和高度。在codeigniter中做什麼是最好的方法?如何在我們上傳時減少codeigniter中圖像的文件大小?

 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()); 
    } 
} 
+0

有沒有錯誤? – Tpojka

+0

正好在image_lib下面調整大小我注意到你已經返回true並返回false? – user4419336

回答

1

我有類似的問題,這是通過本機php功能解決。

貸記pez-cuckowhis original answer。 從它的問題也有一個improvement,但它刪除對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; 
}