Upload de Imagens com PHP

Tags:,
3

Primeiro post sobre PHP. Algumas semans atrás procurei exemplos de scripts que fazem o upload de imagens e já tratem, tamanhos, local do upload, redimencionamento, entre outro, e percebi que esta tudo meio separado, ou o google não me entrega o que eu quero (difícil), rsrsrs.

Então resolvi desenvolver um script, a ideia é facilitar o upload, passar os parametros e a classe cuidar de tudo, inclusive das validações de mime e dimensões.

A classe é grande, 230 linhas por enquanto, conforme eu conseguir otimizar o código eu posto atualizações.

Dúvidas serão bem-vindas.

	
if($_FILES['fileImage']['tmp_name']){
    $options = array("fileName" 	=> $NomeDaImagem
                     ,"extensao" 	=> "jpg"
                     ,"sizes"		=> array(array(1024, 768), array(800, 600), array(133, 100))
                     ,"paths"		=> array("./img/g/", "./img/m/", "./img/p/")
                     ,"validarSize"	=> true
                     ,"corrigirSize" => false);
	
    $up = new UpImage($_FILES['fileImage'], $options);
    if(!$up->execute()) throw new Exception($up->get_error());
    $NomeDaImagem	= $up->get_fileName();
}
	
class UpImage{
	private $file;
	private $mime;
	private $error;
	
	private $fileName;
	private $extensao;
	private $sizes;
	private $paths;
	private $validarSize = false;
	private $corrigirSize = false;
	private $jpgQuality = 80;
	
	public function __construct($file, $options = NULL){
		$this->file = $file;
	
		if($options){
			foreach($options as $prop => $value){
				if(!property_exists(get_class($this), $prop)) throw new Exception("Erro de sistema!");
	
				if(method_exists($this, 'set_'.$prop)){
					call_user_func(array($this, 'set_'.$prop), $value);
				}else{
					$this->$prop = $value;
				}
			}
		}
	
		$this->mime = array("jpeg" 	=> array('application/save', 'image/jpeg', 'image/pjpeg', 'mage/jpeg', 'image/pjpeg'),
							"jpg" 	=> array('application/save', 'image/jpeg', 'image/pjpeg', 'mage/jpeg', 'image/pjpeg'),
							"gif"	=> array('application/save', 'image/gif'),
							"png"	=> array('application/save', 'image/png'));
	
	}
	public function set_fileName($value){$this->fileName = $value;}
	public function set_extensao($value){$this->extensao = str_replace(".", "", $value);}
	public function jpgQuality($value){$this->jpgQuality = $value;}
	
	/*
		array(0 => array(width, height),
			  1 => array(width, height),
			  n => array(width, height));
	
	*/
	public function set_sizes($value){$this->sizes = $value;}
	
	/*
		array(0 => "../img1/",
			  1 => "../img2/",
			  n => "../imgn/",);
	
	*/
	public function set_paths($value){$this->paths = $value;}
	
	public function get_fileName(){return $this->fileName.".".$this->extensao;}
	public function get_error(){return $this->error;}
	
	public function get_uniqPath($dir){
		$path = realpath("./").$dir.$this->get_fileName();
		while(file_exists($path)){
			$this->fileName = uniqid()."_".$this->fileName;
			$path = realpath("./").$dir.$this->get_fileName();
		}
		return $path;
	}
	
	public function execute(){
		if(!$this->sizes || !$this->paths) return false;
	
		$file = &$this->file;
		if($file[error] == 1 || $file[error] == 2){
			$this->error = "O tamanho do arquivo excedeu o limite de 2MB!";
			return false;
		}elseif($file[error] == 3){
			$this->error = "Ocorreu um erro ao copiar o arquivo. Por favor tente novamente!";
			return false;
		}elseif(array_search($file['type'], $this->mime[$this->extensao]) === false){
			$this->error = "A extensão do arquivo deve ser: ".$this->extensao."! - ".$file['type'];
			return false;
		}
	
		if(!$this->fileName){$this->fileName = "img_".uniqid();}
	
		$pathAtual = $file['tmp_name'];
		foreach($this->sizes as $k => $size){
			$path = $this->get_uniqPath($this->paths[$k]);
	
			if($k == 0){
				if($this->validarSize){
					$sAtual = getimagesize($file['tmp_name']);
					if($sAtual[0] != $size[0] || $sAtual[1] != $size[1]) throw new Exception("As dimenções da Imagem estão incorretas! - $sAtual[0]x$sAtual[1] - $size[0]x$size[1]");
					move_uploaded_file($pathAtual, $path);
					$pathAtual = $path;
				}else{
					$this->corrigeWH($size[0], $size[1], $pathAtual, $path);
					$this->diminuir($size[0], $size[1], $pathAtual, $path);
					$pathAtual = $path;
				}
			}else{
				$this->diminuir($size[0], $size[1], $pathAtual, $path);
			}
		}
	
		return true;
	}
	
	public function corrigeWH($baseW, $baseH, $path, $dest){
		$oldimg = $this->my_imagecreate($path);
		$size = getimagesize($path);
		#Tamanhos atuais
		$w = $size[0];
		$h = $size[1];
	
		#Base da proporção
		$bW = $baseW;
		$bH = $baseH;
	
		#Novos tamanhos
		$nW = 0;
		$nH = 0;
	
		if($h > $w){
			$nW = $w;
			$nH = floor($bH * $nW / $bW); #Aplicando a proporção
			$posY = round(($nH/2)-($h/2));
	
			$newimg = imagecreatetruecolor($nW, $nH);
			$bg = imagecolorallocate($newimg, 255, 255, 255);
			imagefill($newimg, 0, 0, $bg);
	
			imagecopyresampled($newimg,$oldimg,0,$posY,0,0,$nW,$nH,$w,$h);
		}else{
			$nH = $h;
			$nW = floor($bW * $nH / $bH);
			$posX = round(($nW/2)-($w/2));
	
			$newimg = imagecreatetruecolor($nW, $nH);
			$bg = imagecolorallocate($newimg, 255, 255, 255);
			imagefill($newimg, 0, 0, $bg);
	
			imagecopyresampled($newimg,$oldimg,$posX,0,0,0,$nW,$nH,$w,$h);
		}
		imagedestroy($oldimg);
		$bg = NULL;
	
		$this->finaliza($newimg, $dest, 100);
	
		imagedestroy($newimg);
		$oldimg = $newimg = NULL;
	}
	
	public function diminuir($nw, $nh, $source, $dest, $rotate = NULL) {
		$size = getimagesize($source);
		#Tamanhos atuais
		$w = $size[0];
		$h = $size[1];
	
		$simg = $this->my_imagecreate($source);
		$dimg = imagecreatetruecolor($nw, $nh);
		$bg = imagecolorallocate($dimg, 255, 255, 255);
		imagefill($dimg, 0, 0, $bg);
		$bg = NULL;
	
		$wm = $w/$nw;
		$hm = $h/$nh;
	
		$h_height = $nh/2;
		$w_height = $nw/2;
	
		if($w > $h) {
			$adjusted_height = $h / $wm;
			$half_height = $adjusted_height / 2;
			$int_height = $half_height - $h_height;
			imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$nw,$adjusted_height,$w,$h);
		} elseif(($w < $h) || ($w == $h)) {
			$adjusted_width = $w / $hm;
			$half_width = $adjusted_width / 2;
			$int_width = $half_width - $w_height;
			imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$nh,$w,$h);
		} else {
			imagecopyresized($dimg, $simg, 0, 0, 0, 0, $nw,$nh,$w,$h);
		}
		imagedestroy($simg); $simg = NULL;
	
		if($rotate){
			$white = imagecolorallocate($dimg, 255, 255, 255);
			$dimg = imagerotate($dimg, $rotate, $white);
			$white = NULL;
		}
	
		$this->finaliza($dimg, $dest);
		imagedestroy($dimg); $dimg = NULL;
	}
	
	public function finaliza($img, $path){
		$ext = $this->extensao;
		switch($ext) {
			case 'gif':
			@imagegif($img,$path);break;
	
			case 'jpg':
			case 'jpeg':
			@imagejpeg($img,$path,$this->jpgQuality);break;
	
			case 'png':
			@imagepng($img,$path);break;
	
			default: $img = NULL; break;
		}
	}
	
	public function my_imagecreate($source){
		$ext = $this->extensao;
		switch($ext) {
			case 'gif':
			$img = imagecreatefromgif($source);break;
	
			case 'jpg':
			case 'jpeg':
			$img = imagecreatefromjpeg($source);break;
	
			case 'png':
			$img = imagecreatefrompng($source);break;
	
			default: $img = NULL; break;
		}
	
		return $img;
	}
}

Comentários para "Upload de Imagens com PHP"

  1. Adriel Esteves says:

    1 – Faltou mostrar um exemplo prático…
    2 – extensao e não extencao…

  2. admin says:

    Po Adriel, valew cara!
    Vou tentar providenciar um exemplo prático e se possível adicionar algumas melhorias na função.

  3. Thanks so much regarding giving everyone an update on this theme on your website. Please realize that if a brand new post appears or in the event that any changes occur with the current post, I would be thinking about reading a lot more and understanding how to make good using of those tactics you reveal. Thanks for your time and consideration of people by making this web site available.

Comente