2017-01-03 66 views
0

我在嘗試使用foreach循環創建縮略圖時遇到問題。我使用CI的內置類image_lib來剪切圖像,但它只會創建第一張圖像的縮略圖,對於其他圖像,它們不會被剪切。這是我的代碼:如何使用Codeigniter創建多個縮略圖

$source[0] = "image/catalog/a.jpg"; 
    $source[1] = "image/catalog/b.jpg"; 
    $source[2] = "image/catalog/c.jpg"; 


    foreach ($source as $image) { 
     $config['image_library'] = 'gd2'; 
     $config['source_image'] = $image; 
     $config['create_thumb'] = TRUE; 
     $config['maintain_ratio'] = TRUE; 
     $config['width'] = 100; 
     $config['height'] = 100; 

     $file = basename($image); 
     $info = pathinfo($file); 
     $file_name = basename($file,'.'.$info['extension']); 
     $config['new_image'] = '/Applications/XAMPP/xamppfiles/htdocs/zhiyuan/image/cache/' . basename($file_name) . '-' . $config['width'] . 'x' . $config['height'] . '.png'; 

     $this->load->library('image_lib', $config); 
     $this->image_lib->resize(); 
    } 

回答

0

問題是我試圖加載庫多次,但似乎它只會加載第一次。爲了剪切第二個圖像,我需要重新初始化配置。以下是修復後的代碼:

$source[0] = "image/catalog/a.jpg"; 
$source[1] = "image/catalog/b.jpg"; 
$source[2] = "image/catalog/c.jpg"; 
$this->load->library('image_lib'); 

foreach ($source as $image) { 
    $config['image_library'] = 'gd2'; 
    $config['source_image'] = $image; 
    $config['create_thumb'] = TRUE; 
    $config['maintain_ratio'] = TRUE; 
    $config['width'] = 100; 
    $config['height'] = 100; 

    $file = basename($image); 
    $info = pathinfo($file); 
    $file_name = basename($file,'.'.$info['extension']); 
    $config['new_image'] = '/Applications/XAMPP/xamppfiles/htdocs/zhiyuan/image/cache/' . basename($file_name) . '-' . $config['width'] . 'x' . $config['height'] . '.png'; 

    $this->image_lib->initialize($config); 
    $this->image_lib->resize(); 
}