Codeigniter è un framework PHP MVC che con semplici istruzioni è possibile realizzare applicazioni web grazie alle classi e metodi disponibili.
Nel tutorial di oggi vedremo come creare una classe per ridimensionare le immagini.

 
< ?php
if (!defined(‘BASEPATH’)) {
exit(‘No direct script access allowed’);
}
 
class imgres {
private $source_file = ;
private $source_file_type = ;
private $source_file_ext = ;
private $original_width = ;
private $original_height = ;
private $original = ;
private $dest_width = ;
private $dest_height = ;
private $resize_mode = ‘auto’;
private $overwrite = false;
private $dest_folder = false;
private $dest_format = false;
private $dest_name = ;
private $crop_x = ;
private $crop_y = ;
private $transparency = true;
private $color_filling = false;
private $fill_color = ‘#FFFFFF’;
private $border_width = 0;
private $border_color = ‘#000000′;
private $watermark_image = ;
private $watermark_x = ;
private $watermark_y = ;
private $params = array();
private $error = ;
 
public function __construct($props = array()) {
$this->initialize($props);
}
 
function initialize($props) {
if (is_array($props) && count($props) > 0) {
foreach($props as $key => $val) {
if(isset($this->$key)) {
$this->$key = $val;
}
}
}
}
 
/*
* Set default values for the class properties
*/

function clear() {
$params = array(
‘source_file’ => ,
‘source_file_type’ => ,
‘source_file_ext’ => ,
‘original_width’ => ,
‘original_height’ => ,
‘original’ => ,
‘dest_width’ => ,
‘dest_height’ => ,
‘resize_mode’ => ‘auto’,
‘overwrite’ => false,
‘dest_folder’ => ,
‘dest_format’ => ,
‘dest_name’ => ,
‘crop_x’ => ,
‘crop_y’ => ,
‘transparency’ => true,
‘color_filling’ => false,
‘fill_color’ => ‘#FFFFFF’,
‘border_width’ => 0,
‘border_color’ => ‘#000000′,
‘watermark_image’ => ,
‘watermark_x’ => ,
‘watermark_y’ =>
);
foreach($params as $key => $val) {
$this->$key = $val;
}
}
 
private function hex_to_rgb($hex) {
if(!preg_match(‘/^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$/’, $hex)) {
return FALSE;
}
 
$hex = str_replace("#", "", $hex);
$color = array();
 
if(mb_strlen($hex) == 3) {
$r = mb_substr($hex, 0, 1);
$g = mb_substr($hex, 1, 1);
$b = mb_substr($hex, 2, 1);
$color[‘r’] = hexdec($r.$r);
$color[‘g’] = hexdec($g.$g);
$color[‘b’] = hexdec($b.$b);
}
else if(mb_strlen($hex) == 6) {
$color[‘r’] = hexdec(mb_substr($hex, 0, 2));
$color[‘g’] = hexdec(mb_substr($hex, 2, 2));
$color[‘b’] = hexdec(mb_substr($hex, 4, 2));
}
 
return $color;
}
 
private function get_extension($file) {
$e = explode(‘.’, $file);
$ext = mb_strtolower($e[count($e)1], ‘UTF-8′);
return $ext;
}
 
private function get_filename($file) {
$file = basename($file);
return mb_substr(mb_strrchr($file, ‘.’, TRUE, ‘UTF-8′), 0, -1, ‘UTF-8′);
}
 
private function get_dest_name() {
$n = ;
$j = 2;
while(file_exists($this->dest_folder.‘/’.$this->dest_name.$n.‘.’.$this->dest_format)) {
$n = ‘_’.$j;
$j++;
}
return $this->dest_name.$n;
}
 
public function get_dst_file() {
$data = array(
‘basename’ => $this->dest_name.‘.’.$this->dest_format,
‘full_path’ => $this->dest_folder.‘/’.$this->dest_name.‘.’.$this->dest_format,
‘dir’ => $this->dest_folder
);
return $data;
}
 
public function get_error() {
return $this->error;
}
 
function process() {
if(!is_file($this->source_file)) {
$this->error = ‘Input file not found!’;
return;
}
 
//Increase memory limits
if (function_exists(‘ini_set’)) {
@ini_set(‘memory_limit’, -1);
ini_set(‘arg_separator.output’ , ‘&amp;’ );
}
 
//Get input file extension
$this->source_file_ext = $this->get_extension($this->source_file);
 
//�п�едел�не �азме�и�е и �ипа на из�одни� �айл
if (function_exists(‘getimagesize’)) {
list($original_width, $original_height, $source_file_type) = getimagesize($this->source_file);
$this->original_width = $original_width;
$this->original_height = $original_height;
$this->source_file_type = $source_file_type;
} else {
$this->error = ‘Image size cannot be determinated’;
return FALSE;
}
 
//Create image resourse
if($this->source_file_type == IMAGETYPE_JPEG) {
$original_img_res = imagecreatefromjpeg($this->source_file);
}
elseif ($this->source_file_type == IMAGETYPE_GIF) {
$original_img_res = imagecreatefromgif($this->source_file);
}
elseif ($this->source_file_type == IMAGETYPE_PNG) {
$original_img_res = imagecreatefrompng($this->source_file);
}
else {
$this->error = ‘File "’.basename($this->source_file).‘" is not valid image file. JPG, PNG and GIF supported only!’;
return FALSE;
}
 
//п�ео�азме��ваме �амо ако нови�е �азме�и �а по-малки о� �ек��и�е
 
if(!is_numeric($this->dest_width) || !is_numeric($this->dest_height)) {
$this->error = ‘You have to specify dest width & height’;
return FALSE;
}
 
//Parse as integers
$this->dest_width = intval($this->dest_width);
$this->dest_height = intval($this->dest_height);
 
$ratio_x = abs(round($this->original_width/$this->dest_width, 2));
$ratio_y = abs(round($this->original_height/$this->dest_height, 2));
 
//Zoom the image so it can fill desired space (desired width & height)
if($this->resize_mode == ‘zoom’) {
$ratio = min($ratio_x, $ratio_y);
 
}
else {
//Resize using $this->dest_width and $this->dest_height as maximum allowed size
$ratio = max($ratio_x, $ratio_y);
}
 
$smallheight = ceil($this->original_height / $ratio);
$smallwidth = ceil($this->original_width / $ratio);
 
//Offset by X and Y
if($this->color_filling == true || $this->resize_mode == ‘zoom’) {
switch($this->crop_x) {
case ‘left’:
$ofx = 0;
break;
 
case ‘right’:
$ofx = $smallwidth;
break;
 
default:
case ‘center’:
$ofx = ceil(($this->dest_width$smallwidth) / 2);
break;
}
 
switch($this->crop_y) {
case ‘top’:
$ofy = 0;
break;
 
case ‘bottom’:
$ofy = $smallheight;
break;
 
default:
case ‘middle’:
$ofy = ceil(($this->dest_height$smallheight) / 2);
break;
}
 
}
else {
$ofx = $ofy = 0;
$this->dest_width = $smallwidth;
$this->dest_height = $smallheight;
}
 
if (function_exists(‘imagecreatetruecolor’)) {
$small = imagecreatetruecolor($this->dest_width, $this->dest_height);
} else {
$small = imagecreate($this->dest_width, $this->dest_height);
}
 
//Keep transparency (if any :) )
if($this->transparency == true && ($this->source_file_type == IMAGETYPE_PNG || $this->source_file_type == IMAGETYPE_GIF)) {
if($this->source_file_type == IMAGETYPE_PNG) {
imagealphablending($small, true);
$colorTransparent = imagecolorallocatealpha($small, 0, 0, 0, 127);
imagefill($small, 0, 0, $colorTransparent);
imagesavealpha($small, true);
}
elseif($this->source_file_type == IMAGETYPE_GIF) {
$trnprt_indx = imagecolortransparent($original_img_res);
if ($trnprt_indx >= 0) {
//its transparent
$trnprt_color = imagecolorsforindex($original_img_res, $trnprt_indx);
$trnprt_indx = imagecolorallocate($small, $trnprt_color[‘red’], $trnprt_color[‘green’], $trnprt_color[‘blue’]);
imagefill($small, 0, 0, $trnprt_indx);
imagecolortransparent($small, $trnprt_indx);
}
}
}
 
//Filling with background color
if($this->color_filling == true) {
if(($fill_color = $this->hex_to_rgb($this->fill_color)) == FALSE) {
$this->error = ‘Invalid background filling color’;
return FALSE;
}
Imagefill($small, 0, 0, imagecolorallocate($small, $fill_color[‘r’], $fill_color[‘g’], $fill_color[‘b’]));
}
 
imagecopyresampled($small, $original_img_res, $ofx, $ofy, 0, 0, $smallwidth, $smallheight, $this->original_width, $this->original_height);
 
//по��ав�не на воден знак
if(is_file($this->watermark_image)) {
//�п�едел�не �азме�и�е на водни� знак
if (function_exists(‘getimagesize’)) {
list($watermark_width, $watermark_height, $watermark_file_type) = getimagesize($this->watermark_image);
}
else {
$this->error = ‘Watermark images size cannot be determinated’;
return FALSE;
}
 
//С�здаване на �е����
if($watermark_file_type == IMAGETYPE_JPEG) {
$watermark_image_res = @imagecreatefromjpeg($this->watermark_image);
}
elseif ($watermark_file_type == IMAGETYPE_GIF) {
$watermark_image_res = @imagecreatefromgif($this->watermark_image);
}
elseif ($watermark_file_type == IMAGETYPE_PNG) {
$watermark_image_res = @imagecreatefrompng($this->watermark_image);
}
else {
$this->error = ‘File "’.basename($this->watermark_image).‘" is not valid watermark image. JPG, PNG and GIF are supported only.’;
return FALSE;
}
 
switch($this->watermark_x) {
case ‘left’:
$watermark_ofx = 0;
break;
 
case ‘right’:
$watermark_ofx = (integer)($this->dest_width$watermark_width);
break;
 
default:
case ‘center’:
$watermark_ofx = (integer)(($this->dest_width/2)($watermark_width/2));
break;
}
 
switch($this->watermark_y) {
case ‘top’:
$watermark_ofy = 0;
break;
 
case ‘middle’:
$watermark_ofy = (integer)(($this->dest_height/2)($watermark_height/2));
break;
 
default:
case ‘bottom’:
$watermark_ofy = (integer)($this->dest_height$watermark_height);
break;
}
 
imagecopyresampled($small, $watermark_image_res, $watermark_ofx, $watermark_ofy, 0, 0, $watermark_width, $watermark_height, $watermark_width, $watermark_height);
}
 
if(is_numeric($this->border_width) && $this->border_width > 0) {
//Parse as integer
$this->border_width = intval($this->border_width);
 
if(($color = $this->hex_to_rgb($this->border_color)) == FALSE) {
$this->error = ‘Invalid border color’;
return FALSE;
}
$rgb_color = imagecolorallocate($small, $color[‘r’], $color[‘g’], $color[‘b’]);
for($i=0; $i< $this->border_width; $i++) {
if (function_exists(‘imagerectangle’)) {
imagerectangle($small, $i, $i, $this->dest_width-($i+1), $this->dest_height-($i+1), $rgb_color);
}
else {
$this->error = ‘Cannot set image border. Function imagerectangle() not found.’;
return FALSE;
}
}
}
 
//If destination folder is not set
if(empty($this->dest_folder)) {
$this->dest_folder = dirname($this->source_file);
}
else {
if(!is_dir($this->dest_folder)) {
$this->error = ‘"’.$this->dest_folder.‘" is not valid destination folder.’;
}
}
//Get absolute path
$this->dest_folder = realpath($this->dest_folder);
//Remove Windows backslashes
$this->dest_folder = str_replace("\\", "/", $this->dest_folder);
//remove leading slashes
$this->dest_folder = rtrim($this->dest_folder, ‘/’);
 
if(empty($this->dest_format)) {
$this->dest_format = $this->source_file_ext;
}
else {
$allowed_formats = array(‘jpg’, ‘gif’, ‘png’);
$this->dest_format = mb_strtolower($this->dest_format, ‘UTF-8′);
if(!in_array($this->dest_format, $allowed_formats)) {
$this->error = ‘Not valid destination format. Use gif, png or jpg’;
return FALSE;
}
}
 
if(empty($this->dest_name)) {
$this->dest_name = $this->get_filename($this->source_file);
}
 
if($this->overwrite == TRUE) {
$dest_full_path = $this->dest_folder.‘/’.$this->dest_name.‘.’.$this->dest_format;
if(file_exists($dest_full_path)) {
if(!@unlink($dest_full_path)) {
$this->error = ‘Cannot overwrite the existing file (‘.$dest_full_path.‘)!’;
return FALSE;
}
}
}
else {
//Add suffix if needed
$this->dest_name = $this->get_dest_name($this->dest_name);
}
 
$dest_full_path = $this->dest_folder.‘/’.$this->dest_name.‘.’.$this->dest_format;
 
//Check quality…
if(!empty($this->quality)) {
if(!is_numeric($this->quality) || $this->quality < 0 || $this->quality > 100) {
$this->error = ‘Not valid image quality set. Use percents between 0 and 100′;
return FALSE;
}
else {
$this->quality = intval($this->quality);
}
}
else {
//Default quality
$this->quality = 100;
}
 
if($this->dest_format == ‘jpeg’ || $this->dest_format == ‘jpg’){
imagejpeg($small, $dest_full_path, $this->quality);
$return = true;
}
elseif($this->dest_format == ‘png’){
imagepng($small, $dest_full_path, intval(($this->quality/10)-1));
$return = true;
}
elseif($this->dest_format == ‘gif’) {
imagegif($small, $dest_full_path, 100);
$return = true;
}
imagedestroy($small);
imagedestroy($original_img_res);
if(isset($return)) {
return $return;
}
else {
$this->error = ‘Error saving the image’;
return FALSE;
}
}
}
?>
 

fonte: www.sastgroup.com ? Vai al post originale