Gerador de Thumbnail (miniatura)
Publicado por Bruno Casella 03/06/2009
[ Hits: 10.396 ]
Uma função que fiz um tempo atrás, com base no livro "PHP para quem sabe PHP". Ela
gera thumbnails (miniaturas) da imagem que você desejar, e retorna o caminho da
imagem gerada.
Está toda comentada, parte em inglês também. Você vai ter que incluir o arquivo
miniatura.php no topo de seu código, então use conforme explicado nos comentários. Ela
está sobre licença GNU. ;)
<?php
/*
* miniatura.php
*
* Copyleft 2006 Bruno Casella <brunocasella@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
?>
<!--
/************************************************************************************************
Função thumbnail criada por Bruno Casella(brunocasella@gmail.com ,*
baseada em exemplo do livro 'PHP para quem conhece PHP' *
com varias implementaçãoes *
(sinta-se a vontade para utiliza-lá e implementá-lá, apenas peço que me mande um email *
com a atualição da função) *
*************************************************************************************************/
/************************************************************************************************
Function thumbnail made by Bruno Casella(brunocasella@gmail.com/bruno.casella@smartis.com.br), *
the base of this is a book ('PHP para quem conhece PHP') *
and here have a lot of implementensions by myself. *
(Fell free to ute this and develop the function. I just ask to mail me the actualized *
function *
*************************************************************************************************/
/*Function is comented mainly in portuguese, that is my own language, and secundary in english, a global language . . .
-->
<?
function calcula_altura($x_img, $y_img, $x_novo)
{
$y_novo=($x_novo*$y_img)/$x_img;
return($y_novo);
}
function calcula_largura($x_img, $y_img, $y_novo)
{
$x_novo=($y_novo*$y_img)/$x_img;
return($x_novo);
}
function miniatura($imagem, $caminho_origem, $caminho_tumb, $tamanho_fixo="", $largura_fixa="", $altura_fixa="", $porcentagem="", $nome_final="")
{
/*$imagem--> o nome da imagem, apenas, que devera ser mandado
$tamanho_fixo--> se será ou não tamanho fixo - se 'S', as variaveis largura_fixa e altura_fixa serão usadas, se 'N' será calculado o tamanho através da porcentagem, que deverá ser mandada
$largura_fixa--> é a largura que será usada na img final(somente se $tamanho_fixo="S")
$altura_fixa--> é a altura que será usada na img final(somente se $tamanho_fixo="S")
--se $largura_fixa=0 e $altura_fixa=0, irá calcular uma img com uma largura definida aqui(por default 50px) e altura calculada por função
$porcentagem--> é a porcentagem que será usada no redimensionamento da img final(somente se $tamanho_fixo="N" ou "")
$nome_final-->o que será acrescentado depois do thumb e antes do nome da img, para poder haver diferenciação entre thumbnails criados da msm img (ex: podera ser criado um thumb_img.jpg e um thumb2_img.jpg da msm img, mas c/ tamanho diferentes
*/
//ah, sim, não se esqueça de que para mandar o argumento $nome final, voce deve mandar todos os anteriores, caso contrario nao dara certo...
/*english comented*/
/*$imagem--> the name of the image, only, tha have to be send
$caminho_origem--> where is the img from. ig: "images/"
$caminho_tumb-->where the thumb is thumb is going to be created. ig: "images/the_thumb_folder/"
/*OBS: the folders of 'where' e 'to' of the img have to have the / on the final of the string, or you'll have a error*//*
$tamanho_fixo--> if the size is gone or not to be fixed - if 'S', the variables largura_fixa and altura_fixa will be utilized, if 'N' will be calculed the zie by the variable 'porcentagem'### if you say 'S' here, and put '0' in $altura_fixa or $largura_fixa , the function will caculate for you the other size...###
$largura_fixa--> the fixed weight of the img (only if $tamanho_fixo="S")
$altura_fixa--> the fixed height of the img (only if $tamanho_fixo="S")
$porcentagem--> its the porcentage that will be used to calculate the new size of the img(only if $tamanho_fixo="N" ou "")
$nome_final-->its going to be acrecented after the 'thumb' and before of the img name, to have a diferent name to two thumbs of the same img
*/
//rebember that to send $nome_final, you have to send all the variables that the function have before the $nome_final, or the function will not work
//o caminho da imagem original(mude conforme o caminho para chegar a sua pasta de imagens sua pasta de imagens)
$caminho_img = $caminho_origem;
$caminho_thumb = $caminho_tumb;
str_replace(" ", "_", $imagem);
str_replace("%", "_", $imagem);
str_replace("%20", "_", $imagem);
$aux=explode(".", $imagem);
if($aux[1]=="gif")
{
$tipo_da_imagem="GIF";
}
else if(($aux[1]=="jpg") || ($aux[1]=="jpeg"))
{
$tipo_da_imagem="JPEG";
}
else if($aux[1]=="bmp")
{
$tipo_da_imagem="GD";
echo "Tipo de imagem inválido";
return("");
}
else if($aux[1]=="png")
{
$tipo_da_imagem="PNG";
}
if($tamanho_fixo=="")
{
$tamanho_fixo="N";
$porcentagem=40;
}
if(!file_exists($caminho_img.$imagem) || $imagem=="")
{
//echo "O arquivo de imagem procurado não existe!";
}
else
{
if(strtoupper($tamanho_fixo)=="N" && ($porcentagem<1 || $porcentagem>100))
{
//echo "O percentual deve estar entre 1 e 100";
}
else
{
//cria o nome da img miniatura
$img_thumb=explode(".",$imagem);
$img_thumb="thumb".$nome_final."_".$img_thumb[0].".jpg";
//lê a img original, e pega seu tamanho
$fun1="ImageCreateFrom".$tipo_da_imagem;
$img_original=$fun1($caminho_img.$imagem);
$origem_x=ImagesX($img_original);
$origem_y=ImagesY($img_original);
//caso não seja tamanho fixo, irá calcular o tamanho da nova img, baseado na porcentagem
if(strtoupper($tamanho_fixo)=="S")
{
if(($largura_fixa==0) || ($altura_fixa==0))
{
if($altura_fixa==0)
{
if($largura_fixa==0) { $largura_fixa=100; }
$x=$largura_fixa;
$aux=getimagesize($caminho_origem.$imagem);
$x_antes=$aux[0];
$y_antes=$aux[1];
$y=calcula_altura($x_antes,$y_antes,$x);
}
else
{
if($altura_fixa==0) { $altura_fixa=150; }
$y=$altura_fixa;
$aux=getimagesize($caminho_origem.$imagem);
$x_antes=$aux[0];
$y_antes=$aux[1];
$x=calcula_largura($x_antes,$y_antes,$y);
}
}
else
{
$x=$largura_fixa;
$y=$altura_fixa;
}
}
else
{
$x=intval($origem_x * $porcentagem/100);
$y=intval($origem_y * $porcentagem/100);
}
//criando a img final, que conterá a miniatura
$img_final = ImageCreateTrueColor($x,$y);
//caso a img miniatura jah exista, não a cria de novo
if(!file_exists($caminho_thumb.$img_thumb))
{
//agora copia a img original, redimensionada, para a imagem final
ImageCopyResampled($img_final, $img_original, 0, 0, 0, 0, $x+1, $y+1, $origem_x, $origem_y);
//salva a nova imagem
$fun2="Image".$tipo_da_imagem;
$fun2($img_final, $caminho_thumb.$img_thumb);
}
//libera a memoria que usou para as duas img's
ImageDestroy($img_original);
ImageDestroy($img_final);
//retorna o caminho para que possa mostrar a nova miniatura
return($caminho_thumb.$img_thumb);
}
}
}
?>
Função para remover acentuação de uma string
Descobrir qual SO o usuário que está acessando o seu site/software está utilizando
Converter String para Maiúsculas
Como extrair chaves TOTP 2FA a partir de QRCODE (Google Authenticator)
Linux em 2025: Segurança prática para o usuário
Desktop Linux em alta: novos apps, distros e privacidade marcam o sábado
IA chega ao desktop e impulsiona produtividade no mundo Linux
Novos apps de produtividade, avanços em IA e distros em ebulição agitam o universo Linux
Como instalar o repositório do DBeaver no Ubuntu
Como instalar o Plex Media Server no Ubuntu
Digitando underscore com "shift" + "barra de espaços"
Como ativar a lixeira e recuperar aquivos deletados em um servidor Linux
Como mudar o nome de dispositivos Bluetooth via linha de comando
O programa assinador digital (0)
dpkg: erro: gatilho de arquivo duplicado chamado pelo arquivo de nome (6)
Instalação não está resolvendo as dependencias (2)
Captação de áudio no zorin linux começa a diminuir com o tempo (5)









