Skip to content

Instantly share code, notes, and snippets.

@gabrielslau
Created March 8, 2012 17:16
Show Gist options
  • Select an option

  • Save gabrielslau/2002153 to your computer and use it in GitHub Desktop.

Select an option

Save gabrielslau/2002153 to your computer and use it in GitHub Desktop.
Controller para redimensionamento e Upload de imagems (e/ou arquivos diversos)
<?php
/**
* Helper to generate thumbnail images dynamically by saving them to the cache.
* Alternative to phpthumb.
*
* Esta classe foi adaptada para o uso da classe VEROT para manipulação das imagens (por Gabriel Lau)
*
* Inspired in http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/
*
* @author Emerson Soares (dev.emerson@gmail.com)
* @filesource https://github.com/emersonsoares/ThumbnailsHelper-for-CakePHP
* @adaptador Gabriel Lau (gabrielslau@yahoo.com.br)
*/
class ThumbnailHelper extends AppHelper {
private $absoluteCachePath = '';
private $cachePath = '';
private $newWidth = 150;
private $newHeight = 225;
private $srcWidth;
private $srcHeight;
private $quality = 80;
private $path = 'files';
private $srcImage = '';
private $srcImageDefault = '/img/preview.jpg';
private $resizeOption = 'auto';
private $openedImage = '';
private $imageResized = '';
public function render($image, $params) {
$this->setup($image, $params);
$path = $this->fixDoubleSlash($this->absoluteCachePath . DS . $this->path . DS . $this->srcImage);
$cachePath = $this->fixDoubleSlash($this->absoluteCachePath . DS . $this->cachePath . DS . $this->srcImage);
if (file_exists(realpath($cachePath))) {
return $this->pathSlash( DS .$this->cachePath . DS . $this->srcImage );
}
elseif (file_exists($path)) {
// $this->Upload = new UploadComponent();
$this->Upload = new UploadComponent(new ComponentCollection());
$this->Upload->upload($path);
$this->Upload->file_overwrite = true;
$this->Upload->file_safe_name = false;
$this->Upload->image_resize = true;
$this->Upload->image_convert = 'jpg';
$this->Upload->jpeg_quality = $this->quality;
// $this->Upload->image_ratio_y = true;
$this->Upload->image_x = $this->newWidth;
$this->Upload->image_y = $this->newHeight;
switch ($this->resizeOption) {
case 'crop':
$this->Upload->image_ratio_crop = 'C';
break;
}
$this->Upload->process($this->cachePath.DS); // Caminho a ser enviado o upload
if (!$this->Upload->processed) {
$this->error = $this->Upload->error;
return $this->srcImageDefault; //Imagem padrão em caso de erro
}
return $this->pathSlash(DS .$this->cachePath . DS . $this->srcImage);
}
}
private function setup($image, $params) {
if (isset($params['path'])) {
$this->path = $params['path'] . DS;
}
if (isset($params['newWidth'])) {
$this->newWidth = $params['newWidth'];
}
if (isset($params['newHeight'])) {
$this->newHeight = $params['newHeight'];
}
if (isset($params['quality'])) {
$this->quality = $params['quality'];
}
if (isset($params['absoluteCachePath'])) {
$this->absoluteCachePath = $params['absoluteCachePath'];
} else {
$this->absoluteCachePath = WWW_ROOT;
}
if (isset($params['resizeOption'])) {
$this->resizeOption = strtolower($params['resizeOption']);
}
if (isset($params['cachePath'])) {
$this->cachePath = $this->pathSlash($params['cachePath'] . DS . $this->newWidth . 'x' . $this->newHeight . DS . $this->quality . DS . $this->resizeOption);
} else {
$this->cachePath = $this->pathSlash('cache' . DS . $this->newWidth . 'x' . $this->newHeight . DS . $this->quality . DS . $this->resizeOption);
}
$this->srcImage = $image;
}
/*
** Funções auxiliares para tratamento do path
*/
private function fixDoubleSlash($path){
$path = str_replace("\\\\", "\\", $path);
$path = str_replace("//", "/", $path);
return $path;
}
private function pathBackslash($path){
$path = str_replace("/", "\\", $path);
return $path;
}
private function pathSlash($path){
$path = str_replace("\\", "/", $path);
return $path;
}
}//end helper
<?php
App::uses('AppController', 'Controller');
/**
* Uploads Controller
*
* @property Upload $Upload
*/
class UploadsController extends AppController {
var $name = 'Uploads';
var $uses = array();
var $components = array('Upload','RequestHandler','Json');
/*function beforeFilter() {
if ($this->action == 'tempUpload') {
$this->Session->id($this->params['pass'][0]);
$this->Session->start();
}
parent::beforeFilter();
}*/
/*
** Faz o upload da imagem para um diretório "temporário"
*/
function tempUpload() {
$this->layout='ajax';
//if (isset($this->params['form']['Filedata'])) {
if (!empty($_FILES)) {
$this->Upload->upload($_FILES['Filedata']);
$json = array();
$minSize = "1024"; //1Kb
//Tamanhos minimos
/*if($this->Upload->image_src_x < 100 || $this->Upload->image_src_y < 100 ){
$json["status"] = "erro";
$json["msg"] = "Imagem muito pequena";
die(json_encode($json));
}*/
if($this->Upload->file_src_size <= $minSize) {
$json["status"] = "erro";
$json["msg"] = "O arquivo é muito pequeno";
die(json_encode($json));
}
$path = "files/tmp/";
$pathpreview = $this->webroot.$path;
$this->Upload->file_name_body_pre = 'temporary_';
$this->Upload->file_max_size = '6291456'; //6MB
$this->Upload->image_resize = true;
$this->Upload->image_convert = 'jpg';
$this->Upload->jpeg_quality = 100;
$this->Upload->image_ratio_y = true;
$this->Upload->image_x = 1280;
$this->Upload->process($path); // Caminho a ser enviado o upload
if ($this->Upload->processed) {
$json["status"] = "ok";
$json["imagem"] = $this->Upload->file_dst_name;
$json['path'] = $path;
$json["msg"] = 'Deu certo';
$json['preview'] = $pathpreview.$this->Upload->file_dst_name;
$json["x"] = $this->Upload->image_dst_x;
$json["y"] = $this->Upload->image_dst_y;
$this->Upload->clean();
die(json_encode($json));
} else {
$json["status"] = "erro";
$json["msg"] = $this->Upload->error;
die(json_encode($json));
}
}//end if !DATA
else{
$json["status"] = "erro";
$json["msg"] = 'Nenhum arquivo foi selecionado';
die(json_encode($json));
}//end EMPTY $_FILES
}//end action
/*
** Redimensiona as imagen "ON THE FLY"
*/
public function resizeImage(){
App::uses('UploadComponent', 'Controller/Component');
$data = $this->params['named'];
$this->autoRender = false;
if(empty($data)){
die("Informe uma imagem para ser redimensionada.");
}else{
$path = '';
if( isset($data['path']) ){$path = str_replace('|', '/',$data['path']);}
$file = empty($path) ? 'files/image/'.$data['file'] : $path.$data['file'];
$x = !isset($data['x']) ? '100' : $data['x'];
$y = !isset($data['y']) ? '100' : $data['y'];
$crop = (isset($data['crop'])) ? $data['crop'] : false;
$fill = (isset($data['fill'])) ? $data['fill'] : false;
$text = (isset($data['text'])) ? $data['text'] : false;
$this->Upload = new UploadComponent(new ComponentCollection());
$this->Upload->upload($file);
$this->Upload->image_resize = true;
$this->Upload->jpeg_quality = 100;
$this->Upload->image_x = $x;
$this->Upload->image_y = $y;
if($text){
$this->Upload->image_text = 'BAzinga';
$this->Upload->image_text_color = '#000000';
$this->Upload->image_text_background_opacity = 40;
$this->Upload->image_text_background = '#FFFFFF';
$this->Upload->image_text_font = 1;
$this->Upload->image_text_position = 'TR';
$this->Upload->image_text_padding_x = 8;
$this->Upload->image_text_padding_y = 2;
}
if($fill) $this->Upload->image_ratio_fill = $fill;
if($crop) $this->Upload->image_ratio_crop = $crop;
$this->Upload->image_background_color = '#ffffff';
$this->RequestHandler->respondAs('Content-type: ' . $this->Upload->file_src_mime);
echo $this->Upload->Process();
//if(!$this->Upload->Process()) echo $this->Upload->error;
die();
}
}//end function resizeImage
}
?>
@gabrielslau

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment