[cakephp] upload images component

Voici un petit composant que j’ai créé afin d’uploader des images facilements dans cakePhp. Il permet en quelques ligne de décider quelles tailles d’ images on veut et dans quels dossier en lui donnant en paramètre des options très simple comme :

$option = array(0 => array('folder'=>'',
 'width'=> 1600,
 'height'=> 1600),
 1 => array('folder'=>'thumb',
 'size'=> '210x310',
 'crop' => true));

voici le code source du composant. Il a été inspiré d’un petit composant d’upload d’image simple.


<?php
/*
 File: /app/controllers/components/QBimage.php
*/
class ImageComponent extends Object
{
 /*
 *    Uploads an images with options : images with max size, cropped images with max height and width.
 *   each image can be put on different folder
 *     Directions:
 *    In view where you upload the image, make sure your form creation is similar to the following
 *    <?= $form->create('FurnitureSet',array('type' => 'file')); ?>
 *
 *    In view where you upload the image, make sure that you have a file input similar to the following
 *    <?= $form->file('Image/name1'); ?>
 *
 *    In the controller, add the component to your components array
 *    var $components = array("QBImage");
 *
 *    In your controller action (the parameters are expained below)
 *    $op = array(0=>array('size'=>1600),
 *               1 => array('folder'=>'thumb', 'crop'=>true, 'size'=>'250x400'));
 *    $filename = $this->Image->upload_images($this->data,"name1","sets",$op);
 *    this returns the file name of the result image.  You can  store this file name in the database
 *
 *    Note that your image will be stored under the $folderName
 *    Image: /webroot/img/$folderName/*
 *
 *    Finally in the view where you want to see the images
 *    <?= $html->image('sets/big/'.$furnitureSet['FurnitureSet']['image_path']);
 *     where "sets" is the folder name we saved our pictures in, and $furnitureSet['FurnitureSet']['image_path'] is the file name we stored in the database

 *    Parameters:
 *    $data: CakePHP data array from the form
 *    $datakey: key in the $data array. If you used <?= $form->file('Image/name1'); ?> in your view, then $datakey = name1
 *    $folderName: the name of the root folder
 *    $options: an array with the upload options
 *               $option = array(0 => array('folder'=>'',
 *                                           'width'=> 1600,
 *                                           'height'=> 1600),
 *                               1 => array('folder'=>'thumb',
 *                                           'size'=> '210x310',
 *                                           'crop' => true));
 */

 function upload_images($data, $datakey, $folderName, $options=null) {

 if (strlen($data['Image'][$datakey]['name'])>4){
 $error = 0;

 if(!is_array($options))
 {
 $options=array(0=>array('folder'=>'','height'=>1600));
 }
 if(isset($options[0]) &&  !is_array($options[0]))
 {
 $options=array(0=>$options);
 }else
 if(isset($options[1]) &&  !is_array($options[1]))
 {
 $options=array(0=>$options);
 }

 $tempuploaddir = "img/temp"; // the /temp/ directory, should delete the image after we upload
 $biguploaddir = "img/".$folderName."/"; // the /big/ directory
 $smalluploaddir = "img/".$folderName."/small/";

 // Make sure the required directories exist, and create them if necessary
 if(!is_dir($tempuploaddir)) mkdir($tempuploaddir,0777);
 if(!is_dir("img/".$folderName)) mkdir("img/".$folderName,0777);

 $filetype = $this->getFileExtension($data['Image'][$datakey]['name']);
 $filetype = strtolower($filetype);

 if (($filetype != "jpeg")  && ($filetype != "jpg") && ($filetype != "gif") && ($filetype != "png"))
 {
 // verify the extension
 echo 'Mauvaise extension';
 return false;
 }
 else
 {
 // Get the image size
 $imgsize = GetImageSize($data['Image'][$datakey]['tmp_name']);
 }

 // Generate a unique name for the image (from the timestamp)
 $id_unic = str_replace(".", "", strtotime ("now"));
 $filename = $id_unic;

 settype($filename,"string");
 $filename.= ".";
 $filename.=$filetype;
 $tempfile = $tempuploaddir . "/$filename";

 if (is_file($data['Image'][$datakey]['tmp_name']) || is_uploaded_file($data['Image'][$datakey]['tmp_name']))
 {
 // Copy the image into the temporary directory
 if (!copy($data['Image'][$datakey]['tmp_name'],"$tempfile"))
 {
 print "Error Uploading File!.";
 exit();
 }
 else {
 /*
 *    Generate the big version of the image with max of $imgscale in either directions
 */

 foreach($options as $op)
 {
 if(empty($op['height']))
 {
 if(empty($op['width']))
 {
 if(empty($op['size']))
 {
 $op['height']=$op['width']=1600;
 }
 else
 {
 if(is_numeric($op['size']))
 {
 $op['height']=$op['width']=$op['size'];
 }
 else
 {
 list($op['width'],$op['height']) = explode('x',$op['size']);
 }
 }
 }
 else{
 $op['height']=$op['width'];
 }
 }
 if(empty($op['width']))
 {
 $op['width']=$op['height'];
 }
 if(empty($op['folder']))
 {
 $op['folder']='';
 }
 if(empty($op['crop']))
 {
 $op['crop']=false;
 }
 $op['_filename'] = $filename;
 $op['_foldername'] = "img/".$folderName."/";

 if(!$op['crop'])
 {
 if(!$this->resize_img($tempfile, $op))
 {
 return false;
 }
 }
 else{
 if(!$this->crop_but_keep_ratio($tempfile, $op))
 {
 return false;
 }
 }
 }

 // Delete the temporary image
 unlink($tempfile);
 }

 }
 else
 return false;
 // Image uploaded, return the file name
 return $filename;
 }
 }

 function crop_but_keep_ratio($imgname, $op) {

 $fixeWidth = $op['width'];
 $fixeHeight = $op['height'];
 $filename = $op['_foldername'].$op['folder'].'/'.$op['_filename'];

 $filetype = $this->getFileExtension($imgname);
 $filetype = strtolower($filetype);
echo 'A-';
 switch($filetype){
 case "jpeg":
 case "jpg":
 $img_src = ImageCreateFromjpeg ($imgname);
 break;
 case "gif":
 $img_src = imagecreatefromgif ($imgname);
 break;
 case "png":
 $img_src = imagecreatefrompng ($imgname);
 break;
 }
 $width = imagesx($img_src);
 $height = imagesy($img_src);
 $fixeRatio = $fixeHeight / $fixeWidth;
 $realRatio = $height / $width;

 if($fixeRatio<$realRatio)// la nouvelle image sera plus étalé que l'ancienne
 {
 $newheight = $fixeWidth*$realRatio;
 $newwidth = $fixeWidth;
 }
 else// la nouvelle image sera plus étalé que l'ancienne
 {
 $newwidth = $fixeHeight/$realRatio;
 $newheight = $fixeHeight;
 }
 //-- Calculate resampling

 //-- Calculate cropping (division by zero)
 $cropx = ($newwidth - $fixeWidth != 0) ? ($newwidth - $fixeWidth) / 2 : 0;
 $cropy = ($newheight - $fixeHeight != 0) ? ($newheight - $fixeHeight) / 2 : 0;

 //-- Setup Resample & Crop buffers
 $resampled = imagecreatetruecolor($newwidth, $newheight);
 $cropped = imagecreatetruecolor($fixeWidth, $fixeHeight);

 //-- Resample
 imagecopyresampled($resampled, $img_src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
 //-- Crop
 imagecopy($cropped, $resampled, 0, 0, $cropx, $cropy, $newwidth, $newheight);

 // Save the cropped image
 switch($filetype)
 {
 case "jpeg":
 case "jpg":
 if(!imagejpeg($cropped,$filename,80))
 return false;
 break;
 case "gif":
 if(!imagegif($cropped,$filename,80))
 return false;
 break;
 case "png":
 if(!imagepng($cropped,$filename,80))
 return false;
 break;
 }
 return false;

 }

 function resize_img($imgname, $op)    {

 if($op['width']>$op['height'])
 {
 $size = $op['height'];
 }
 else{
 $size = $op['width'];
 }
 $filename = $op['_foldername'].$op['folder'].'/'.$op['_filename'];

 $filetype = $this->getFileExtension($imgname);
 $filetype = strtolower($filetype);

 switch($filetype) {
 case "jpeg":
 case "jpg":
 $img_src = ImageCreateFromjpeg ($imgname) ;
 break;
 case "gif":
 $img_src = imagecreatefromgif ($imgname);
 break;
 case "png":
 $img_src = imagecreatefrompng ($imgname);
 break;
 }
 //  if(empty($img_src)) return false;

 $true_width = imagesx($img_src);
 $true_height = imagesy($img_src);

 if ($true_width>=$true_height)
 {
 $width=$size;
 $height = ($width/$true_width)*$true_height;
 }
 else
 {
 $width=$size;
 $height = ($width/$true_width)*$true_height;
 }
 $img_des = ImageCreateTrueColor($width,$height);
 imagecopyresampled ($img_des, $img_src, 0, 0, 0, 0, $width, $height, $true_width, $true_height);

 // Save the resized image
 switch($filetype)
 {
 case "jpeg":
 case "jpg":
 imagejpeg($img_des,$filename,80);
 break;
 case "gif":
 imagegif($img_des,$filename,80);
 break;
 case "png":
 imagepng($img_des,$filename,9);
 break;
 }
 return true;
 }

 function getFileExtension($str) {

 $i = strrpos($str,".");
 if (!$i) { return ""; }
 $l = strlen($str) - $i;
 $ext = substr($str,$i+1,$l);
 return $ext;
 }
} ?>

Comments are closed.