Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
Nome: Upload
Versão: 20080520
Requisito: PHP5, GD2
Funcionalidade: Classe para o envio de imagens com possibilidade de gerar miniaturas utilizando métodos de crop e marca d'água. :)
Exemplos: Utilizando Crop, Utilizando Marca d'água (Caravelas, BA)
Comentários: Mais um dentre os muitos scripts encontrados na web para upload de imagens e para gerar miniaturas. A documentação não é lá grande coisa mas dá pra entender, procurei deixar o código bem limpo para o bom entendimento. Livre para compartilhar e adaptar. ;)
Segue abaixo um exemplo de utilização:
CODE
<?php
include("upload.class.php");
// Instanciando a classe passando $_FILES e uma sugestão de nome das imagens geradas.
$obj = new Upload($_FILES['arquivo'], "upload_test");
// Vetor de segurança, o qual será utilizado para fazer a verificação da imagem submetida.
// Estes são as quatro possibilidades de chave deste vetor. Nenhuma delas é obrigatória.
$arr_validation = array(
'min_dimension' => 480,
'max_dimension' => 1024,
'mime' => array('image/jpg', 'image/jpeg'),
'max_size' => 614400
);
// Verificando se a imagem passará pelo método de validação.
if( !$obj->validation($arr_validation) )
{
echo "<pre>";
print_r($obj->getError());
echo "</pre>";
}
else
{
// Criando uma miniatura com os quatro lados iguais.
$obj->createSquareThumb(100, "uploads");
// Criando uma miniatura proposrcionalmente menor.
$obj->createThumb(640, "uploads", '_thumb', "marcadagua.png");
// Mesma imagem submetida salva no diretório.
$obj->send("uploads");
}
?>
CODE
<?php
/**
* Upload
*
* Class to upload images and generate thumbnail using crop and watermark methods
*
* @author Paulo A. G. Rodrigues <pauloandreget@gmail.com>
* @copyright Copyright © 2008, Paulo A. G. Rodrigues
* @license http://creativecommons.org/licenses/by-sa/3.0
* @version 20080520
* @link http://www.salvavidasgetsemani.com
*/
/**
* Changelog
*
* 20080520 - Requirements: PHP5
*
* 20080518 - Method to create thumbnail divided for square and normal
*
* 20080516 - Implements flexible methods on validation. Users can set your own parameters.
*
* 20080507 - Adaptation for extension of files (case sensitive)
*
* 20080312 - Documentation of code
* - Add validation method with: mime type, size and dimension of image
* - New watermark method for thumbnail generated
*
* 20080311 - Initial release
*/
class Upload
{
private $file;
private $file_uploaded;
private $image_size;
private $suggest_name;
private $errors = array();
/**
* Constructor
*
* @param array superglobal $_FILES
* @param string suggest name of generated image or false for automatic name
*/
function __construct( $superglobal, $suggest_name = false )
{
$this->file = $superglobal;
$this->image_size = getimagesize($superglobal['tmp_name']);
$this->suggest_name = ( !$suggest_name ) ? md5(mktime()) : $suggest_name;
}
/**
* Validation method for size, dimension and mime type
*
* @param array
* @return boolean
*/
public function validation( $arr_validation )
{
$array_keys = array_keys($arr_validation);
if( in_array('max_size', $array_keys) )
{
if( $this->file['size'] > $arr_validation['max_size'] )
{
array_push($this->errors, "Muito grande");
}
}
if( in_array('mime', $array_keys) )
{
if( !in_array($this->image_size['mime'], $arr_validation['mime']) )
{
array_push($this->errors, "Tipo inválido");
}
}
if( in_array('max_dimension', $array_keys) )
{
if( $this->image_size[0] > $arr_validation['max_dimension'] || $this->image_size[1] > $arr_validation['max_dimension'] )
{
array_push($this->errors, "Dimensões maiores");
}
}
if( in_array('min_dimension', $array_keys) )
{
if( $this->image_size[0] < $arr_validation['min_dimension'] || $this->image_size[1] < $arr_validation['min_dimension'] )
{
array_push($this->errors, "Dimensões menores");
}
}
if( count($this->errors) > 0 )
{
return false;
}
else
{
return true;
}
}
/**
* Upload method
*
* @param string folder of image destination
* @return void
*/
public function send( $dest )
{
$info = pathinfo($this->file['name']);
$name = $this->suggest_name . '.' . strtolower($info['extension']);
if( move_uploaded_file($this->file['tmp_name'], $dest . '/' . $name) )
{
$this->setFileUploaded($dest . '/' . $name);
}
else
{
$this->setFileUploaded(false);
}
}
/**
* Create and save square thumbnail
*
* @param integer max size of thumbnail
* @param string folder of thumbnail destination
* @param string name sufix for new image
* @param string image path of watermark or false for don't use watermark
* @return void
*/
public function createSquareThumb( $size, $dest = "", $sufix = '_square', $watermark = false )
{
$image_w = $this->image_size[0];
$image_h = $this->image_size[1];
$scale = $image_w / $image_h;
if( $scale < 1 )
{
$thumb_w = $size;
$thumb_h = round($size / $scale);
$centerX = 0;
$centerY = round( ($thumb_h - $thumb_w) / 2 );
}
else
{
$thumb_w = round($size * $scale);
$thumb_h = $size;
$centerX = round( ($thumb_w - $thumb_h) / 2 );
$centerY = 0;
}
$info = pathinfo($this->file['name']);
if( preg_match('/(jpg|jpeg)/i', $info['extension']) )
{
$image_orig = imagecreatefromjpeg($this->file['tmp_name']);
}
else if( preg_match('/(gif)/i', $info['extension']) )
{
$image_orig = imagecreatefromgif($this->file['tmp_name']);
}
else if( preg_match('/(png)/i', $info['extension']) )
{
$image_orig = imagecreatefrompng($this->file['tmp_name']);
}
$ptX = imagesx($image_orig);
$ptY = imagesy($image_orig);
$image_fin = imagecreatetruecolor($size, $size);
imagecopyresampled($image_fin, $image_orig, -$centerX, -$centerY, 0, 0, $thumb_w, $thumb_h, $image_w, $image_h);
imageconvolution($image_fin, array(array(-1,-1,-1), array(-1,16,-1), array(-1,-1,-1)), 8, 0);
if( $watermark )
{
$img_info = getimagesize($watermark);
$base = pathinfo($watermark);
if( preg_match('/(jpg|jpeg)/i', $base['extension']) )
{
$logo = imagecreatefromjpeg($watermark);
}
else if( preg_match('/(gif)/i', $base['extension']) )
{
$logo = imagecreatefromgif($watermark);
}
else if( preg_match('/(png)/i', $base['extension']) )
{
$logo = imagecreatefrompng($watermark);
}
$size_x = imagesx($image_fin);
$size_y = imagesy($image_fin);
imagealphablending($image_fin, true);
imagecopymerge($image_fin, $logo, 0, ($size_y - $img_info[1]), 0, 0, $size_x, imagesy($logo), 60);
imagedestroy($logo);
}
$name = $this->suggest_name . $sufix . '.' . strtolower($info['extension']);
if( preg_match('/(jpg|jpeg)/i', $info['extension']) )
{
imagejpeg($image_fin, $dest . '/' . $name, 90);
}
else if( preg_match('/(gif)/i', $info['extension']) )
{
imagegif($image_fin, $dest . '/' . $name);
}
else if( preg_match('/(png)/i', $info['extension']) )
{
imagepng($image_fin, $dest . '/' . $name, 90);
}
$this->setFileUploaded($dest . '/' . $name);
imagedestroy($image_orig);
imagedestroy($image_fin);
}
/**
* Create and save thumbnail
*
* @param integer max size of thumbnail
* @param string folder of thumbnail destination
* @param string name sufix for new image
* @param string image path of watermark or false for don't use watermark
* @return void
*/
public function createThumb( $size, $dest = "", $sufix = '_thumb', $watermark = false )
{
$image_w = $this->image_size[0];
$image_h = $this->image_size[1];
$scale = min($size/$image_w, $size/$image_h);
if( $scale < 1 )
{
$thumb_w = round($scale * $image_w);
$thumb_h = round($scale * $image_h);
}
else
{
$thumb_w = $image_w;
$thumb_h = $image_h;
}
$info = pathinfo($this->file['name']);
if( preg_match('/(jpg|jpeg)/i', $info['extension']) )
{
$image_orig = imagecreatefromjpeg($this->file['tmp_name']);
}
else if( preg_match('/(gif)/i', $info['extension']) )
{
$image_orig = imagecreatefromgif($this->file['tmp_name']);
}
else if( preg_match('/(png)/i', $info['extension']) )
{
$image_orig = imagecreatefrompng($this->file['tmp_name']);
}
$ptX = imagesx($image_orig);
$ptY = imagesy($image_orig);
$image_fin = imagecreatetruecolor($thumb_w, $thumb_h);
imagecopyresampled($image_fin, $image_orig, 0, 0, 0, 0, $thumb_w, $thumb_h, $image_w, $image_h);
if( $watermark )
{
$img_info = getimagesize($watermark);
$base = pathinfo($watermark);
if( preg_match('/(jpg|jpeg)/i', $base['extension']) )
{
$logo = imagecreatefromjpeg($watermark);
}
else if( preg_match('/(gif)/i', $base['extension']) )
{
$logo = imagecreatefromgif($watermark);
}
else if( preg_match('/(png)/i', $base['extension']) )
{
$logo = imagecreatefrompng($watermark);
}
$size_x = imagesx($image_fin);
$size_y = imagesy($image_fin);
imagealphablending($image_fin, true);
imagecopymerge($image_fin, $logo, 0, ($size_y - $img_info[1]), 0, 0, $size_x, imagesy($logo), 60);
imagedestroy($logo);
}
$name = $this->suggest_name . $sufix . '.' . strtolower($info['extension']);
if( preg_match('/(jpg|jpeg)/i', $info['extension']) )
{
imagejpeg($image_fin, $dest . '/' . $name, 90);
}
else if( preg_match('/(gif)/i', $info['extension']) )
{
imagegif($image_fin, $dest . '/' . $name);
}
else if( preg_match('/(png)/i', $info['extension']) )
{
imagepng($image_fin, $dest . '/' . $name);
}
$this->setFileUploaded($dest . '/' . $name);
imagedestroy($image_orig);
imagedestroy($image_fin);
}
/**
* Set method
*
* @param string name of generated image or false for upload error
* @return void
*/
public function setFileUploaded( $name )
{
$this->file_uploaded = $name;
}
/**
* Get method
*
* @return string / array
*/
public function getFileUploaded()
{
return $this->file_uploaded;
}
public function getArraySuperglobal()
{
return $this->file;
}
public function getArrayImage()
{
return $this->image_size;
}
public function getError()
{
return $this->errors;
}
}
?>
Classe em ação: http://pauloandreget.webspace.com.br/thumb.php (O servidor é free, então possivelmente deve dar alguns erros..)
Os dois vetores exibidos neste exemplo após o upload representa a superglobal *$_FILES* e as características da imagem temporária. [http://forum.imasters.com.br/public/style_emoticons/](http://forum.imasters.com.br/public/style_emoticons/)default/thumbsup.gif
[http://forum.imasters.com.br/public/style_emoticons/](http://forum.imasters.com.br/public/style_emoticons/)default/excl.gif *NOTA:* Caso o segundo parâmetro do construtor da classe não esteja definido, o nome será gerado automaticamente baseado nas funções *mktime()* e *md5()*. Como neste exemplo eu defini, todos os uploads de teste terão o mesmo endereço, a cada teste haverá a sobreposição.
Thas all folks! Não é uma brastemp mas funciona! :P
Em especial agradeço ao bimonti pela contribuição na parte de crop. :D
Carregando comentários...