FORUM DARKERS

Tecnologia & Informática => Programação => PhP/Html => Topic started by: rog on 28 de April , 2006, 09:58:41 AM

Title: criar imagems miniaturas [script][critica]
Post by: rog on 28 de April , 2006, 09:58:41 AM
ae

esse script e muito bem anotado no hotscripts.com

eu achei ele muito ruim

<?php

/*
Version 1&#46;0 Created by&#58; Ryan Stemkoski
Questions or comments&#58; ryan@ipowerplant&#46;com
Visit us on the web at&#58; http&#58;//www&#46;ipowerplant&#46;com
Purpose&#58;  This script can be used to resize one or more images&#46;  It will save the file to a directory and output the path to that directory which you 
  can display or write to a databse&#46; 

TO USE, SET&#58; 
$filename = image to be resized
$newfilename = added to filename to for each use to keep from overwriting images created example thumbnail_$filename is how it will be saved&#46;
$path = where the image should be stored and accessed&#46; 
$newwidth = resized width could be larger or smaller
$newheight = resized height could be larger or smaller

SAMPLE OF FUNCTION&#58; makeimage('image&#46;jpg','fullimage_','imgs/',250,250)

Include the file containing the function in your document and simply call the function with the correct parameters and your image will be resized&#46;

*/
 
//IMAGE RESIZE FUNCTION FOLLOW ABOVE DIRECTIONS
function makeimage($filename,$newfilename,$path,$newwidth,$newheight) {

//SEARCHES IMAGE NAME STRING TO SELECT EXTENSION (EVERYTHING AFTER &#46; )
$image_type strstr($filename'&#46;');

//SWITCHES THE IMAGE CREATE FUNCTION BASED ON FILE EXTENSION
switch($image_type) {
case '&#46;jpg'&#58;
$source imagecreatefromjpeg($filename);
break;
case '&#46;png'&#58;
$source imagecreatefrompng($filename);
break;
case '&#46;gif'&#58;
$source imagecreatefromgif($filename);
break;
default&#58;
echo("Error Invalid Image Type");
die;
break;
}

//CREATES THE NAME OF THE SAVED FILE
$file $newfilename &#46; $filename;

//CREATES THE PATH TO THE SAVED FILE
$fullpath $path &#46; $file;

//FINDS SIZE OF THE OLD FILE
list($width$height) = getimagesize($filename);

//CREATES IMAGE WITH NEW SIZES
$thumb imagecreatetruecolor($newwidth$newheight);

//RESIZES OLD IMAGE TO NEW SIZES
imagecopyresized($thumb$source0000$newwidth$newheight$width$height);

//SAVES IMAGE AND SETS QUALITY || NUMERICAL VALUE = QUALITY ON SCALE OF 1-100
imagejpeg($thumb$fullpath60);

//CREATING FILENAME TO WRITE TO DATABSE
$filepath $fullpath;

//RETURNS FULL FILEPATH OF IMAGE ENDS FUNCTION
return $filepath;

}

?>

o que acham
Title: Re: criar imagems miniaturas [script][critica]
Post by: whit3_sh4rk on 28 de April , 2006, 10:26:59 AM
Essa parada de criar miniatura de imagens eu acho bem interessante e prático, ao invés de fazer isso manualmente..

Mas não entendo de PHP.. porque você acha esse script ruim?

[]s
Title: Re: criar imagems miniaturas [script][critica]
Post by: rog on 28 de April , 2006, 12:33:07 PM
ae WS

o script esta totalemente ruim (nota 0 mesmo)

eu postei ele para os membres que entendem de php estudar e apontar os defeitos dele e postar aqui

se ninguem achar nada, depois eu explico tudo

rog
Title: Re: criar imagems miniaturas [script][critica]
Post by: caesar2k on 28 de April , 2006, 06:18:35 PM
o script tem o switch case sensitive, não funcionaria com JPg JPG jPG jPg etc
ele tem que salvar o arquivo ao invés de criar na memória e fazer um stream do novo jpg, e pode acabar com o espaço de hosting de um site de usado para o mal, usando uma imagem grande por exemplo, e criar multiplos requests de nova imagem, cada uma com um nome diferente
ainda, mesmo que a imagem seja criada, se houver outra com o mesmo nome, a outra será sobrescrita

Pelo menos foram essas os erros que encontrei no código, e são bem gritantes mesmo
Title: Re: criar imagems miniaturas [script][critica]
Post by: rog on 28 de April , 2006, 07:41:30 PM
hehe

valeu caesar

o script esta em :
http://hotscripts.com/search/9914141.html (http://hotscripts.com/search/9914141.html)

$image_type = strstr($filename, '.'); // a ultima ocorença depois de um ponto no nome do arquivo vai determinar o tipo da imagem

como o caesar2K falou FOTO1.GIF nao vai passar pela condiçao $image_type == '.gif'
tambem foto1.jpeg nao vai passar pela condiçao $image_type =='.jpg':
-----------------------------------------------------------------
imagejpeg($thumb, $fullpath, 60); // isso so funciona com imagem criada com imagecreatefromjpeg($filename);
nao funcionara com gif nem com png

$filepath = $fullpath; // isso e desnecessario (stupido)
   
//RETURNS FULL FILEPATH OF IMAGE ENDS FUNCTION
return $filepath;
############################################

o cara poderia incluir o formato bmp tambem

rog
Title: Re: criar imagems miniaturas [script][critica]
Post by: Shady on 28 de April , 2006, 09:03:27 PM
Muito bom post... como exatamente voce modificaria o script, rog?

 Obrigado ao cesar2k tambem!
Title: Re: criar imagems miniaturas [script][critica]
Post by: rog on 28 de April , 2006, 11:16:41 PM
pensei para o site da minha cliente (no momente esta hospedada em casa) http://rgirardin.dyndns.org/helena (http://rgirardin.dyndns.org/helena)

as paginas da galleria estavam muito pesadas

o prob e que a cliente nao entende nada e que eu nao faço manutençao de site (nem faço site, so se for complicado)

entao fize varias funçoes para fazer mirror entre as fotos e as miniaturas

1)
########################################################################################################################
function verif_vignette_dir(){
#
global $foto_dir;
global $vignette_dir;
#
    if($dir = opendir($foto_dir))
    {
        while($file = readdir($dir))
        {
            if($file !="." && $file != "..")
            {
                if(is_dir($foto_dir."/".$file))
                {
if(!is_dir($vignette_dir."/".$file))
{
if(!mkdir($vignette_dir."/".$file))
{
return false;
}
else
{
chmod($vignette_dir."/".$file,0777);
}
}
                }
            }
        }
        closedir($dir);
    }
    else
{
echo "<b>ERREUR : mirroring $foto_dir to $vignette_dir</b>";
exit();
}
return TRUE;
}

2)
########################################################################################################################
function check_vignette_dir(){
#
global $foto_dir;
global $vignette_dir;
#
    if($dir = @opendir($vignette_dir))
    {
        while($file = readdir($dir))
        {
            if($file !="." && $file != "..")
            {
                if(is_dir($vignette_dir."/".$file))
                {
if(!is_dir($foto_dir."/".$file))
{
if(!delete_dir($vignette_dir."/".$file))
{
echo "<b>ERREUR : $file</b> impossible d'effacer le dossier !!\n<br>";
}
}
                }
            }
        }
        closedir($dir);
    }
    else
{
echo "<b>ERREUR : $foto_dir</b> n'est pas un dossier !!\n<br>scan_dir($foto_dir)";
exit();
}
}
#

3)
########################################################################################################################
function check_mirror(){
#
global $foto_dir;
global $vignette_dir;
#
if($dir = opendir($vignette_dir))
{
while($file = readdir($dir))
{
if(is_dir($vignette_dir."/".$file) && $file !="." && $file != "..")
{
if($dir2 = opendir($vignette_dir."/".$file))
{
while($file2 = readdir($dir2))
{
if(is_file($vignette_dir."/".$file."/".$file2) &&  $file2 !="." && $file2 != "..")
{
if(!is_file($foto_dir."/".$file."/".$file2))
{
if(!unlink($vignette_dir."/".$file."/".$file2))
{
echo "<b>ERREUR : </b><br>unable to delete  $vignette_dir."/".$file."/".$file2 !!";
}
}
}
}
}
closedir($dir2);
}

}
}
closedir($dir);
}
#

4)
function update_vignette(){
#
global $foto_dir;
global $vignette_dir;
global $width_foto;
global $height_foto;
#
if($dir = opendir($foto_dir))
{
while($file = readdir($dir))
{
if(is_dir($foto_dir."/".$file) && $file !="." && $file != "..")
{
if($dir2 = opendir($foto_dir."/".$file))
{
while($file2 = readdir($dir2))
{
if(is_file($foto_dir."/".$file."/".$file2) &&  $file2 !="." && $file2 != "..")
{
if(!is_file($vignette_dir."/".$file."/".$file2))
{
$size = getimagesize($foto_dir."/".$file."/".$file2);
#
$ratio_width = $size[0]/$width_foto ;
$ratio_height = $size[1]/$height_foto ;
#
if($ratio_height < $ratio_width)
{
$ratio = $ratio_width;
}
else
{
$ratio = $ratio_height;
}
#
$new_width = ceil($size[0]/$ratio);
$new_height = ceil($size[1]/$ratio);
#
$image_type = trim(substr(strstr($size['mime'],'/'),1));
###########################################################################
if($image_type == "jpeg")
{
$resized_img = imagecreatefromjpeg($foto_dir."/".$file."/".$file2);
}
elseif($image_type == "gif")
{
$resized_img = imagecreatefromgif($foto_dir."/".$file."/".$file2);
}
elseif($image_type == "png")
{
$resized_img = imagecreatefrompng($foto_dir."/".$file."/".$file2);
}
elseif($image_type == "bmp")
{
$resized_img = imagecreatefromwbmp($foto_dir."/".$file."/".$file2);
}
else
{
# bad file type
print('<li>'.$foto_dir."/".$file."/".$file2);
}
###########################################################################
$thumb ="";
#
if($thumb = imagecreatetruecolor($width_foto,$height_foto))
{
$color = imagecolorallocate($thumb,255,255,255);
imagefilledrectangle($thumb,0,0,$width_foto ,$height_foto , $color);
}
#
$x_dest = ceil(($width_foto - $new_width)/2);
$y_dest = ceil(($height_foto - $new_height)/2);
#
if(!imagecopyresampled($thumb,$resized_img,$x_dest,$y_dest,0,0,$new_width,$new_height,$size[0],$size[1]))
{
print ("imagecopyresized($thumb,$resized_img, 0, 0, 0, 0,$new_width,$new_height,$size[0],$size[1])");
}
###########################################################################
if($image_type == "jpeg")
{
imagejpeg($thumb,$vignette_dir."/".$file."/".$file2,60);
}
elseif($image_type == "gif")
{
imagegif($img,$foto_dir."/".$file."/".$file2);
}
elseif($image_type == "png")
{
imagepng($img,$foto_dir."/".$file."/".$file2);
}
elseif($image_type == "bmp")
{
imagewbmp($img,$foto_dir."/".$file."/".$file2);
}
else
{
# bad file type
}
imagedestroy($resized_img);
imagedestroy($thumb);
}
}
}
}
closedir($dir2);
}
}
}
closedir($dir);
}
#

assim a pagina que chama a atualizaçao e
elseif(isset($_GET['op']) && $_GET['op']==5)
{
########################################################################################################################
#
# update the vignette dir
#
########################################################################################################################
#
# 1 checking if the vignette dir is mirroring to foto dir
verif_vignette_dir();
# 2 checking for deprecated dir in vignette dir
check_vignette_dir();
# 3 checking for deprecated file in vignette dir
check_mirror();
# 4 checking for missing vignette files and creating new one
update_vignette();
#
redirect($_SERVER['PHP_SELF']."?op=3");
}
Title: Re: criar imagems miniaturas [script][critica]
Post by: kmrafa on 05 de May , 2006, 04:08:22 PM
kara..n manjo de php..quase nada..

sera que dava pra você explicar que que faz esse códigos que você passou?

valew rog..
Title: Re: criar imagems miniaturas [script][critica]
Post by: rog on 05 de May , 2006, 07:07:57 PM
function verif_vignette_dir()

ele verifica se todas as pastas em $foto_dir estao tambem em $vignette_dir (miniatura)
se na existir, a funçao crias a pasta com o mesmo nome (sincronisation) em vignette_dir

function check_vignette_dir()

ele verifica se existe pasta em $vignette_dir que nao estao em $foto_dir
se fora o caso, a funçao delete a pasta em $vignette_dir

check_mirror()
ele verifica se existe arquivos em $vignette_dir que nao estao em $foto_dir
se for o caso, a miniatura em $vignette_dir e apagada

update_vignette()
ele lista todas fotos em $foto_dir, compara com a pasta $vignette_dir se tever miniatura faltando, o script cria a miniatura
e ponha no lugar certo em $vignette_dir

assim, cada vezes que modificar a pasta $foto, e so aciopnar a pagina que o script esta updated

 ;D

rog
Title: Re: criar imagems miniaturas [script][critica]
Post by: Cloudy on 05 de May , 2006, 10:56:17 PM
Tambem não entendo muito de PHP, mas são bem interessantes essas funções.

Meus parabéns.

...by Cloudy
Title: Re: criar imagems miniaturas [script][critica]
Post by: kmrafa on 16 de May , 2006, 06:24:37 PM
Quote from: "rog"function verif_vignette_dir()

ele verifica se todas as pastas em $foto_dir estao tambem em $vignette_dir (miniatura)
se na existir, a funçao crias a pasta com o mesmo nome (sincronisation) em vignette_dir

function check_vignette_dir()

ele verifica se existe pasta em $vignette_dir que nao estao em $foto_dir
se fora o caso, a funçao delete a pasta em $vignette_dir

check_mirror()
ele verifica se existe arquivos em $vignette_dir que nao estao em $foto_dir
se for o caso, a miniatura em $vignette_dir e apagada

update_vignette()
ele lista todas fotos em $foto_dir, compara com a pasta $vignette_dir se tever miniatura faltando, o script cria a miniatura
e ponha no lugar certo em $vignette_dir

assim, cada vezes que modificar a pasta $foto, e so aciopnar a pagina que o script esta updated

 ;D

rog

ahh legal.... mto interessante...

isso quebra um galho legal..

mais ae..você conhece um script bom que faça o mesmo serviço? ou o que tenha pra modifica pra esse fica bom??

vlw rog =)