Ir para conteúdo
Fórum Script Brasil
  • 0

Imagem thumbs código ótimo mais...


dougty

Pergunta

O código é ótimo mais gostaria que ao invés de mostrar a thumbs (ex. thumbs.php?w=100&h=100&imagem=teste.jpg) gostaria que ele salva-se a imagem thumb no diretório. Já tentei de tudo não consegui alguém, me ajuda =]

<?php

header("Content-type: image/jpeg");

$im = imagecreatefromjpeg($_GET['imagem']); // Cria uma nova imagem a partir de um arquivo ou URL

$wid = (int)$_GET["w"];

$hei = (int)$_GET["h"];

$w = imagesx($im);

$h = imagesy($im);

$w1 = $w / $wid;

if ($hei == 0)

{

$h1 = $w1;

$hei = $h / $w1;

}

else

{

$h1 = $h / $hei;

}

// echo "$h1 - $w1";

$min = min($w1,$h1);

$xt = $min * $wid;

$x1 = ($w - $xt) / 2;

$x2 = $w - $x1;

$yt = $min * $hei;

$y1 = ($h - $yt) / 2;

$y2 = $h - $y1;

$x1 = (int) $x1;

$x2 = (int) $x2;

$y1 = (int) $y1;

$y2 = (int) $y2;

$img = NULL;

$img = imagecreatetruecolor($wid, $hei);

//$background = imagecolorallocate($img, 50, 50, 50);

imagecolorallocate($img,255,255,255);

$c = imagecolorallocate($img,255,255,255);

$c1 = imagecolorallocate($img,0,0,0);

for ($i=0;$i<=$hei;$i++)

{

imageline($img,0,$i,$wid,$i,$c);

}

imagecopyresampled($img,$im,0,0,$x1,$y1,$wid,$hei,$x2-$x1,$y2-$y1);

imagejpeg($img);

?>

Editado por dougty
Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

Cara, eu não sei exatamente o que tu quer, mas se queres mecher com imagens e diretórios, eu criei uma bibliotecasinha boa pra isso. Eu já parei de atualiza-la porque estou trabalhando em um framework mais completo, mas por enquanto, é ela que me quebra o galho.

Segue:

arquivo: DirectoryManager.php

<?php

class File {

    private $path = '';
    private $pathToDirectory = '';
    private $baseName = '';
    private $fileName = '';
    private $extension = '';
    
    public function __construct($path) {
        
        if($pathInfo = pathinfo($path)) {
            $this->path = $path;
            $this->pathToDirectory = $pathInfo['dirname'];
            $this->baseName = $pathInfo['basename'];
            $this->fileName = $pathInfo['filename'];
            if(isSet($pathInfo['extension']))
                $this->extension = $pathInfo['extension'];
        } else throw new Exception('Não é um caminho válido para um arquivo');    
    }
    
    public function getPath() {
        
        return $this->path;
    }
    
    public function getRealPath() {
        
        return realpath($this->path);
    }
    
    public function getPathToDirectory() {
        
        return $this->pathToDirectory.DIRECTORY_SEPARATOR;
    }
    
    public function getBaseName() {
        
        return $this->baseName;
    }
    
    public function getFileName() {
        
        return $this->fileName;
    }
    
    public function getExtension() {
        
        return $this->extension;
    }
    
    public function isFile() {
        
        return is_file($this->getPath());
    }
    
    public function isDirectory() {
        
        return is_dir($this->getPath());
    }
    
    public function isReadable() {
        
        return is_readable($this->getPath());
    }

    public function isWritable() {
        
        return is_writable($this->getPath());
    }
    
    public function isExecutable() {
        
        return is_executable($this->getPath());
    }
    
    public function delete() {
        return @unlink($this->getPath());
    }
    
}

class DirectoryManager {

    private $pathToDirectory = '';
    private $files = array();
    private $filesIndex = -1;
    private $handleResource = null;
    
    public function __construct($pathToDirectory = './') {
        
        if(!is_dir($pathToDirectory))
            throw new Exception('Caminho especificado não corresponde a um diretório');
        
        if($pathToDirectory[strlen($pathToDirectory)-1] != DIRECTORY_SEPARATOR)
            $pathToDirectory[strlen($pathToDirectory)] = DIRECTORY_SEPARATOR;
            
        $this->pathToDirectory = $pathToDirectory;
        
        if($this->handleResource = opendir($this->pathToDirectory)) {
            while($file = readdir($this->handleResource))
                $this->files[] = new File($this->getPathToDirectory().$file);
        }
        
    }
    
    public function __destruct() {
        
        if(closedir($this->handleResource) && array_key_exists($this->handleResource, $this->files))
            unset($filesInDirectory[$this->handleResource]);
            
    }
    
    public function getPathToDirectory() {
        
        return $this->pathToDirectory.DIRECTORY_SEPARATOR;
    }
    
    public function getRealPathToDirectory() {
        
        return realpath($this->getPathToDirectory());
    }
    
    public function getNextFile() {
        
        if(++$this->filesIndex >= count($this->files))
            return null;
        return $this->files[$this->filesIndex];
    }
    
    public function getPreviousFile() {
        
        if(--$this->filesIndex <= -1)
            return null;
        return $this->files[$this->filesIndex];
    }
    
    public function contains(File $file) {
        
        foreach($this->files as $localFiles) {
            if($localFiles->getBaseName() == $file->getBaseName())
                return true;
        }
        
        return false;
    }
    
    public function getFiles() {
        
        return $this->files;
    }
    
    public function getHandleResource() {
        
        return $this->handleResource;
    }
    
    public function getNumberOfFiles() {
        
        foreach($this->getFiles() as $file)
            if($file->isFile())
                $numberOfFiles++;
        
        return $numberOfFiles;
    }
    
    public function isReadable() {
        
        return is_readable($this->pathToDirectory);
    }

    public function isWritable() {
        
        return is_writable($this->pathToDirectory);
    }
    
    public function isExecutable() {
        
        return is_executable($this->pathToDirectory);
    }
    
}
arquivo: Image.php
<?php

class Image {

    private $path = '';
    private $image = null;
    private $width = 0;
    private $height = 0;
    private $newImage = null;

    public function __construct($pathToImage , $imageFormat = 'jpg') {
        
        if(!is_file($pathToImage))
            throw new Exception('O caminho informado não corresponde a um arquivo válido');
        $this->path = realpath($pathToImage);
        
        if(count($extension = explode('.', basename($this->path))) >= 2)
            $imageFormat = strToLower($extension[count($extension)-1]);
        else 
            $imageFormat = strToLower($imageFormat);
        
        switch($imageFormat) {
            case 'gif' : $this->image = @imagecreatefromgif($this->path); break;
            case 'png' : $this->image = @imagecreatefromgif($this->path); break;
            case 'jpg' : case 'jpeg' :
                default : $this->image = @imagecreatefromjpeg($this->path);
        }    
        
        if(!$this->image)
            throw new Exception('Erro ao abrir imagem: formato não suportado');
        
        $this->newImage = $this->image;
        $this->width = imagesX($this->image);
        $this->height = imagesY($this->image);
    }
    
    public function save($path, $imageFormat = 'jpg') {
        if(($newPath = dirname($path)) != '.')
            $newPath .= DIRECTORY_SEPARATOR.basename($path);
        else
            $newPath = $this->path.DIRECTORY_SEPARATOR.basename($path);
        
        if(count($extension = explode('.', basename($path))) >= 2)
            $imageFormat = strToLower($extension[count($extension)-1]);
        else 
            $imageFormat = strToLower($imageFormat);
        
        switch($imageFormat) {
            case 'gif' : return @imagegif($this->newImage, $newPath); break;
            case 'png' : return @imagepng($this->newImage, $newPath); break;
            case 'jpg' : case 'jpeg' : 
                default : return @imagejpeg($this->newImage, $newPath);
        }
    }
    
    private function resize($width, $height) {
        $this->newImage = imageCreateTrueColor($width, $height);
        return imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->width,  $this->height);
    }
    
    public function resizeXY($width, $height = 0) {
        
        if(!$width && !$height)
            throw new Exception('É necessario especificar um tamanho maior que 0 para largura e altura');
            
        if(!$width || !$height)
            if($width && !$height)
                $height = $this->height / $this->width * $width;
            else if(!$width && $height)
                $width = $this->width / $this->height * $height;
            
        return $this->resize($width, $height);
    }
    
    public function resizePercent($width, $height) {
        $width = $width? $this->width / 100 * $width : $this->width;
        $height = $height? $this->height / 100 * $height : $this->height;
        
        return $this->resize($width, $height);
    }
    
    public function restoreChanges() {
        $this->newImage = $this->image;
    }
    
    public function getOriginalImage() {
        
        return $this->image;
    }
    
    public function getModifiedImage() {
        
        return $this->newImage;
    }
    
    public function getOriginalWidth() {
        return $this->width;
    }
    
    public function getOriginalHeight() {
        return $this->height;
    }
    
    public function getModifiedWidth() {
        return imagesX($this->newImage);
    }
    
    public function getModifiedHeight() {
        return imagesY($this->newImage);
    }
    
}

Se tu entender como funciona logo de cara, fica a dica, senão, me diz o que tu quer fazer e eu faço uma versão utilizando essas bibliotecas.

Abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Muito obrigado pela ajuda...

Eu mesmo acabei resolvendo, segue função criada:

<?php function reduz_imagem($nome_img, $wid, $hei) { 
      $im =  imagecreatefromjpeg($nome_img);
     
      $w = imagesx($im);
      $h = imagesy($im);
    
      $w1 = $w / $wid;
      if ($hei == 0)
      {
        $h1 = $w1;
        $hei = $h / $w1;
      }
      else
      {
        $h1 = $h / $hei;
      }
      $min = min($w1,$h1);  
       
      $xt = $min * $wid;
      $x1 = ($w - $xt) / 2;
      $x2 = $w - $x1;      

      $yt = $min * $hei;
      $y1 = ($h - $yt) / 2;
      $y2 = $h - $y1;      
      
    $x1 = (int) $x1;
    $x2 = (int) $x2;
    $y1 = (int) $y1;
    $y2 = (int) $y2;                
    
    $img = NULL;
    
    $img = imagecreatetruecolor($wid, $hei); 
    imagecolorallocate($img,255,255,255); 

    $c  = imagecolorallocate($img,255,255,255); 
    $c1 = imagecolorallocate($img,0,0,0); 
     
    for ($i=0;$i<=$hei;$i++)
    {
      imageline($img,0,$i,$wid,$i,$c);
    }
      
    imagecopyresampled($img,$im,0,0,$x1,$y1,$wid,$hei,$x2-$x1,$y2-$y1);    

    imagejpeg($img, $nome_img, 100);
} ?>

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      652k
×
×
  • Criar Novo...