本文實(shí)例講述了CI框架實(shí)現(xiàn)遞歸生成文件路徑并重新生成圖片功能。分享給大家供大家參考,具體如下:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); set_time_limit(0); class Img_build extends CI_Controller{ private static $img_path = 'upload_old/'; private static $new_path = 'upload/'; function __construct() { parent::__construct(); } /** * 獲取需要讀取的路徑的信息 * $map = array ( * '路徑名' => array (文件1, 文件2, 文件3) * ) */ public function index() { $this->load->helper('directory'); //讀取路徑的信息 $map = directory_map(self::$img_path, FALSE, TRUE); echo "<pre>"; print_r($map); echo "</pre>"; if(!empty($map) && is_array($map)) { $this->build_path($map); } } /** * 遞歸生成相應(yīng)的路徑 * @param array $map */ private function build_path($map = array()) { if(!file_exists(self::$new_path)) { mkdir(self::$new_path, 0777); } foreach($map as $key => $val) { $old_img_path = self::$img_path; $old_tmp_path = self::$img_path.$key.'/'; $new_img_path = self::$new_path; $new_tmp_path = self::$new_path.$key.'/'; if(is_dir($old_tmp_path)) { //echo $new_tmp_path; if(!file_exists($new_tmp_path)) { mkdir($new_tmp_path, 0777); } self::$img_path = $old_tmp_path; self::$new_path = $new_tmp_path; echo 'path:'.self::$img_path."<hr>"; $this->load->helper('directory'); $c_map = directory_map($old_tmp_path, FALSE, TRUE); // echo "<pre>"; // print_r($c_map); // echo "</pre>"; if(!empty($c_map) && is_array($c_map)) { $this->build_path($c_map); } } if(is_file(self::$img_path.$val)) { echo 'file:'.self::$img_path.$val."<hr>"; $img = array(); $img['source_image'] = self::$img_path.$val; $img['new_image'] = self::$new_path.$val; $this->build_img($img); } self::$img_path = $old_img_path; self::$new_path = $new_img_path; } } /** * 根據(jù)原圖片生成新的圖片 * @param array $img * $img = array('source_image'=> '原圖片的路徑', 'new_image' => '新圖片路徑') */ private function build_img($img = array()) { if(!is_array($img) || empty($img)) { return FALSE; } //設(shè)置圖像生成參數(shù) $config['image_library'] = 'gd2'; //設(shè)置圖像庫 $config['source_image'] = $img['source_image']; //設(shè)置原始圖像的名字/路徑 $config['create_thumb'] = FALSE; //讓圖像處理函數(shù)產(chǎn)生一個(gè)預(yù)覽圖像 $config['maintain_ratio'] = TRUE; //指定是否在縮放或使用硬值的時(shí)候使圖像保持原始的縱橫比例 //$config['quality'] = 200; $img_info = array(); $img_info = getimagesize($config['source_image']);//獲取圖片的尺寸 if(is_array($img_info) && !empty($img_info)) { $config['width'] = $img_info[0]; $config['height'] = $img_info[1]; } $config['new_image'] = $img['new_image']; //新圖片路徑 $this->load->library('image_lib', $config); //加載圖片處理類 $this->image_lib->initialize($config); //調(diào)用 if ( ! $this->image_lib->resize()) { echo $this->image_lib->display_errors(); } $this->image_lib->clear(); //清除圖片處理參數(shù) } } ?>
希望本文所述對大家基于CodeIgniter框架的PHP程序設(shè)計(jì)有所幫助。