Jump to content
Fórum Script Brasil
  • 0

PHP GD - juntar fotos


lags cap
 Share

Question

Boa tarde amigos, já revirei a internet a procura de uma função que utilize a biblioteca GD para unir vários arquivos de imagem em um só, mas não encontrei nada.

Alguém pode sugerir um?

Preciso de uma função que pegue todas as imagens de um diretório "x" e una-as uma ao lado da outra, na horizontal.

Testei alguns scripts mas nada funcionou.

Caso alguém conheça, preciso gerar estas imagens para trabalhar com CSS SPRITES.

Grato

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Olá

Consegui editar uma classe para unir as imagens que preciso.

Agora basta SALVAR esta imagem no pc após gerá-la

Não estou conseguindo salvar, o código gera perfeitamente mas não copia a imagem para o pc.

Segue o código:

<?php

$sprite = new spritify();


$files = glob("test_images/10-*home*.*");

for ($i=1; $i<count($files); $i++)
 { 
$num = $files[$i];

 $sprite->add_image($num, "jpeg");

 //echo $num;

 }





//retrieving error
$arr = $sprite->get_errors();
//if there are any then output them
if(!empty($arr))
{
    foreach($arr as $error)
    {
        echo "<p>".$error."</p>";
    }
}
else
{
    //returns GD image resource
    //$img = $sprite->get_resource();
    
    //outputs image to browser
    $sprite->output_image();    
}

/************************************************************* 
 * This script is developed by Arturs Sosins aka ar2rsawseen, http://webcodingeasy.com 
 * Fee free to distribute and modify code, but keep reference to its creator 
 *
 * This class can generate CSS sprite image from multiple provided images
 * Generated image can be outputted to browser, saved to specified location, etc.
 * This class also generates CSS code for sprite image, using element ID's provided with image.
 * It facilitates CSS sprite implementations to existing website structures
 * 
 * For more information, examples and online documentation visit:  
 * http://webcodingeasy.com/PHP-classes/CSS-sprite-class-for-creating-sprite-image-and-CSS-code-generation
**************************************************************/
class spritify
{
    //image type to save as (for possible future modifications)
    private $image_type = "png";
    //array to contain images and image informations
    private $images = array();
    //array for errors
    private $errors = array();
    
    //gets errors
    public function get_errors(){
        return $this->errors;
    }
    
    /*
     * adds new image
     * first parameter - path to image file like ./images/image.png
     * second parameter (optiona) - ID of element fro css code generation
     */
    public function add_image($image_path, $id="elem"){
        if(file_exists($image_path))
        {
            $info = getimagesize($image_path);
            if(is_array($info))
            {
                $new = sizeof($this->images);
                $this->images[$new]["path"] = $image_path;
                $this->images[$new]["width"] = $info[0];
                $this->images[$new]["height"] = $info[1];
                $this->images[$new]["mime"] = $info["mime"];
                $type = explode("/", $info['mime']);
                $this->images[$new]["type"] = $type[1];
                $this->images[$new]["id"] = $id;
            }
            else
            {
                $this->errors[] = "Provided file \"".$image_path."\" isn't correct image format";
            }
        }
        else
        {
            $this->errors[] = "Provided file \"".$image_path."\" doesn't exist";
        }
    }
    
    //calculates width and height needed for sprite image
    private function total_size(){
        $arr = array("width" => 0, "height" => 0);
        foreach($this->images as $image)
        {
            if($arr["height"] < $image["height"])
            {
                $arr["height"] = $image["height"];
            }
            $arr["width"] += $image["width"];
        }
        return $arr;
    }
    
    //creates sprite image resource
    private function create_image(){
        $total = $this->total_size();
        $sprite = imagecreatetruecolor($total["width"], $total["height"]);
        imagesavealpha($sprite, true);
        $transparent = imagecolorallocatealpha($sprite, 0, 0, 0, 127);
        imagefill($sprite, 0, 0, $transparent);
        $top = 0;
    $side = 0;
        foreach($this->images as $image)
        {
            $func = "imagecreatefrom".$image['type'];
            $img = $func($image["path"]);
            imagecopy( $sprite, $img, $side, ($total["height"] - $image["height"]), 0, 0,  $image["width"], $image["height"]);


//imagecopy( $sprite, $img, ($total["width"] - $image["width"]), $top, 0, 0,  $image["width"], $image["height"]);

            $top += $image["height"];
            $side += $image["width"];
        }
        return $sprite;

    }
    
    //outputs image to browser (makes php file behave like image)
    public function output_image(){
        $sprite = $this->create_image();
        header('Content-Type: image/'.$this->image_type);
        $func = "image".$this->image_type;
        $func($sprite); 
        ImageDestroy($sprite);
    }
    
    /*
     * generates css code using ID provided when adding images or pseido ID "elem"
     * $path parameter (optional) - takes path to already generated css_sprite file or uses default file for pseudo code generation
     */
    public function generate_css($path = "/css_sprite.png"){
        $total = $this->total_size();
        $top = $total["height"];
        $css = "";
        foreach($this->images as $image)
        {
            if(strpos($image["id"],"#") === false)
            {
                $css .= "#".$image["id"]." { ";
            }
            else
            {
                $css .= $image["id"]." { ";
            }
            $css .= "background-image: url(".$path."); ";
            $css .= "background-position: ".($image["width"] - $total["width"])."px ".($top - $total["height"])."px; ";
            $css .= "width: ".$image['width']."px; ";
            $css .= "height: ".$image['height']."px; ";
            $css .= "}\n";
            $top -= $image["height"];
        }
        return $css;
    }
    
    /*
     * if $path provided, than saves image to path
     * else forces image download
     */
    public function safe_image($path = ""){
        $sprite = $this->create_image();
        $func = "image".$this->image_type;
        if(trim($path) == "")
        {
            header('Content-Description: File Transfer');
            header('Content-Type: image/'.$this->image_type);
            header('Content-Disposition: attachment; filename=css_sprite.'.$this->image_type);
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($sprite));
            ob_clean();
            flush();
            $func($sprite); 

    
        }
        else
        {
            $func($sprite, $path); 

        }

        ImageDestroy($sprite);
    }
    
    //return image resource
    public function get_resource(){
        $sprite = $this->create_image();

        return $sprite;
    }
}

    

?>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share



  • Forum Statistics

    • Total Topics
      150.8k
    • Total Posts
      648.8k
×
×
  • Create New...