Nossos pensamentos, nossas atitudes, nossas emoções, tudo são formas de energia, constantemente influenciando o mundo a nossa volta. (Diane Dreher)

logo Moraga  
Principal
Categorias
Ferramentas

telescópio

Semanal Mensal Geral
  1. Converter Byte em KB, MB, GB, TB, EB
  2. Verificar CPF com PHP
  3. Jogo da velha ou Tic tac toe
  4. Captcha em PHP
  5. createElement - Solução compatível com os navegadores
  6. removeChild - Remover elementos HTML por Javascript
  7. Copiando tabelas e removendo registros duplicados no MySQL
  8. Gerando Thumbnails com PHP
  9. Removendo linhas e espaços em branco de strings
  10. Apache Expires Header - Cache de imagens, Javascript e CSS
  1. Converter Byte em KB, MB, GB, TB, EB
  2. Verificar CPF com PHP
  3. Captcha em PHP
  4. Jogo da velha ou Tic tac toe
  5. Copiando tabelas e removendo registros duplicados no MySQL
  6. createElement - Solução compatível com os navegadores
  7. removeChild - Remover elementos HTML por Javascript
  8. Gerando Thumbnails com PHP
  9. Removendo linhas e espaços em branco de strings
  10. Apache Expires Header - Cache de imagens, Javascript e CSS
  1. Converter Byte em KB, MB, GB, TB, EB
  2. Captcha em PHP
  3. Jogo da velha ou Tic tac toe
  4. createElement - Solução compatível com os navegadores
  5. Copiando tabelas e removendo registros duplicados no MySQL
  6. Apache Expires Header - Cache de imagens, Javascript e CSS
  7. Removendo linhas e espaços em branco de strings
  8. removeChild - Remover elementos HTML por Javascript
  9. Verificar se existe um valor no Array em Javascript
  10. Gerando Thumbnails com PHP
e-mail Enviar por e-mail imprimir Imprimir
PHP

Gerando Thumbnails com PHP

Por Alejandro Fernandez Moraga

Flickrgrab Thumbnail Gallery<br/>Foto por <a rel="nofollow" href="http://www.flickr.com/photos/dominicspics/2373684421/">Dominic's pics</a> Flickrgrab Thumbnail Gallery
Foto por Dominic's pics

Thumbnail é a cópia de uma imagem em tamanho e dimensão reduzida. O principal objetivo do Thumbnail na web é reduzir o tempo de download das páginas usando miniaturas ao invés das imagens originais, diminuindo o tamanho da página.

A classe Thumbnail aceita os seguintes formatos:

  • jpg/jpeg
  • gif
  • png

Métodos

  • __construct( $imagem, [ $width=80 ], [ $height=80 ] ): Construtor da classe, requer o caminho da imagem a partir da qual serão gerados os Thumbnails. Os parâmetros $width e $height são opcionais, definem respectivamente a largura e altura do Thumbnail em pixels.

  • setWidth( $width ): Define a largura do Thumbnail em pixels.

  • setHeight( $height ): Define a altura do Thumbnail em pixels.

  • setSize( $width, $height ): Define a largura e altura do Thumbnail em pixels.

  • Create( [ $filename ] ): Cria ou exibe o Thumbnail.

Exemplos e Aplicações

Grava o Thumbnail no mesmo diretório da imagem original

$thumbnail = new Thumbnail('/var/www/imagens/equipe.jpg');
$thumbnail->Create('equipe-thumb'); // Gera o Thumbnail /var/www/imagens/equipe-thumb.jpg

O método Create identifica se o parâmetro é um diretório ou um nome. Se for um nome, o Thumbnail é gravado no mesmo diretório da imagem original.

Atenção: Não coloque a extensão do arquivo no método Create, o Thumbnail assume a extensão da imagem original. Se a imagem for um jpg o Thumbnail será um jpg, se a imagem for um gif o Thumbnail será um gif e assim por diante.

Grava o Thumbnail em outro diretório

$thumbnail = new Thumbnail('/var/www/imagens/logo.jpg');
$thumbnail->Create('/var/www/imagens/thumbs/logo'); // Gera o Thumbnail logo.jpg

O caminho do diretório do Thumbnail pode ser absoluto (caminho físico) ou relativo.

$thumbnail = new Thumbnail('http://www.exemplo.com.br/imagem.jpg');
$thumbnail->Create();

Exibe um Thumbnail da imagem em 80x80 pixels.

Grava e exibe o Thumbnail

$thumbnail = new Thumbnail('http://www.exemplo.com.br/imagem.jpg');
$thumbnail->Create('./imagem2');
$thumbnail->Create();

A chamada do método Create com argumento salva o Thumbnail no servidor.

Grava múltiplos Thumbnails com diferentes tamanhos

$thumbnail = new Thumbnail('./imagem.gif');

$thumbnail->setSize(50, 50);
$thumbnail->Create('imagem-50x50'); // Grava Thumbnail de 50x50 pixels

$thumbnail->setSize(70, 70);
$thumbnail->Create('imagem-70x70'); // Grava Thumbnail de 70x70 pixels

$thumbnail->setSize(120, 120);
$thumbnail->Create('imagem-120x120'); // Grava Thumbnail de 120x120 pixels

Um imagem pode gerar inúmeros Thumbnails. Para cada Thumbnail é definido a largura e altura da imagem no método setSize e depois armazenado no servidor Create.

Tratamento de Exceções

try {
	$thumbnail = new Thumbnail('./arquivo.doc');
	...
}
catch (Exception $e) {
	echo 'Arquivo inválido';
}

O construtor da classe verifica se extensão da imagem é uma extensão válida, a imagem deve ser um jpeg/jpg, png ou gif. Se a imagem tiver uma extensão diferente é gerado exceção.

Código fonte

<?php
/**
 * Gera Thumbnails de imagens.
 * Extensões suportadas: jpeg, jpg, png, gif.
 * 
 * @author Alejandro Fernandez Moraga
 * @link http://www.moraga.com.br/artigo/php/69/gerando-thumbnail-em-php/
 * @version 1.1
 */

class Thumbnail {
	
	/**
	 * Caminho da imagem original.
	 *
	 * @var string
	 */
	private $image;
	
	/**
	 * Extensão da imagem original.
	 *
	 * @var string
	 */
	private $extension;
	
	/**
	 * Extensão utilizada nas funções de manipulação de imagem do PHP.
	 *
	 * @var string
	 */
	private $extension_r;
	
	/**
	 * Largura do Thumbnail em pixels. Padrão: 80
	 *
	 * @var integer
	 */
	private $width;
	
	/**
	 * Altura do Thumbnail em pixels. Padrão: 80
	 *
	 * @var integer
	 */
	private $height;
	
	/**
	 * Construtor da classe.
	 *
	 * @param string $image Imagem original.
	 * @param integer $width Largura do Thumbnail em pixels.
	 * @param integer $height Altura do Thumbnail em pixels.
	 */
	public function __construct($image, $width=80, $height=80) {
		$this->image = $image;
		
		if (!@preg_match('@\.(jpg|jpeg|png|gif)@', $this->}image, $extension))
			throw new Exception('type of image unsupported');
		
		$this->extension = $extension[1];
		$this->extension_r = ($extension[1] == 'jpg') ? 'jpeg' : $extension[1];
		$this->width = $width;
		$this->height = $height;
	}
	
	/**
	 * Define a largura do Thumbnail.
	 *
	 * @param integer $width Largura do Thumbnail em pixels.
	 */
	public function setWidth($width) {
		$this->width = $width;	
	}
	
	/**
	 * Define a altura do Thumbnail.
	 *
	 * @param interger $height Altura do Thumbnail em pixels.
	 */
	public function setHeight($height) {
		$this->height = $height;
	}
	
	/**
	 * Define a largura e altura do Thumbnail.
	 *
	 * @param integer $width Largura do Thumbnail em pixels.
	 * @param interger $height Altura do Thumbnail em pixels.
	 */
	public function setSize($width, $height) {
		$this->width = $width;
		$this->height = $height;
	}
	
	/**
	 * Cria ou exibe o Thumbnail.
	 * Retorna o caminho da thumbnail quando o parâmetro $filename é informado e o thumbnail é armazenado em disco.
	 *
	 * @param string $filename Caminho para salvar o arquivo.
	 * @return string|null Caminho da thumbnail gerada.
	 */
	public function Create($filename=NULL) {

		$functions = array(
			'imagecreatefrom'.$this->extension_r,
			'image'.$this->extension_r,
		);

		list($image_width, $image_height) = getimagesize($this->image);
		
		// Regra de três para encontrar a largura ou altura da thumbnail, caso um dos dados seja omitido.
		$this->width = (!$this->width) ? ($this->height * $image_width)/$image_height : $this->width;
		$this->height = (!$this->height) ? ($this->width * $image_height)/$image_width : $this->height;
		
		$thumbnail = imagecreatetruecolor($this->width, $this->height);
		
		imagecopyresized($thumbnail, $functions[0]($this->image), 0, 0, 0, 0, $this->width, $this->height, $image_width, $image_height);
		
		if ($filename) {
			$filename = ((strpos($filename, '/') !== false) ? $filename : preg_replace('@\/([^/]+)$@', '/', $this->image).$filename).'.'.$this->extension;
			imagejpeg($thumbnail, $filename);
			return $filename;
		}
		else {
			header("Content-Type: image/{$this->extension_r}");
			imagejpeg($thumbnail);
		}
	}
}

?>

Atualizações

  • 15/09/2008: se a largura ou altura for omitida, então é assumido um valor proporcional. Sugestão de Fábio.

Comentários
  • Rodrigo Córdula (http://www.rodrigocordula.com.br) 25 de Fevereiro de 2010 18:50

    Meu irmão você é o cara,
    Fiz um pequeno teste e a parada funciou beleza.
    Só tem um pequenino pro na linha 58 da classe:

    if (!@preg_match('@\.(jpg|jpeg|png|gif)@', $this-[ESTA CHAVE AQUI] ->"}"image, $extension))

    Meus parabéns, não tinha conhecimento sobre imagecopyresized e outras paradas.

    Obrigado por estas informações.
    att,
    Rodrigo


Comentar
captcha