Menu Principal
  O que é PHP-GTK ?
  Lista de discussões
  Fórum de discussões
  Documentação
  Ver Artigos
  Ver Aplicações
  Users Map
  Para Linux
  Para Windows

 Login
 Login
 Senha
  Efetuar Cadastro
  Esqueci a Senha

 Busca no Site
Parceiros


PHP-GTK Brasil :: Girando Imagens
Título
Girando Imagens
Resumo
Uma função que gira a imagem de 90 em 90 graus que não utiliza a biblioteca GD a qual deveria ter sido compilada com o Php Nativamente o Php5-cli do Ubuntu não tem a função de girar então eu fiz uma pesquisas e consegui uma maneira de girar as figuras.

Texto
Primeiro podemos aproveitar para verificar na pratica como criar uma janela, um botao , label, GtkEntry, e o Fixed
e como abrir um dialogo para abrir arquivos, a foto girada é mostrada em um objeto dialogo separado.
Como a função que precisariamos a imagerotate não existe entao criamos a image_rotate mas ela so aceita 90,270,180,360 graus (no proximo exemplo eu mostro de grau em grau)
Observo que não foi feito nenhum tratamento na imagem para evitar serrilhado ou perda de cor
para utilizar coloque o programa onde preferir, rode o programa, escolha o angulo, escolha o endereço da figura, mostre a figura e mande girar
no diretorio onde esta o programa surgira um arquivo com o nome imagemgirada

Código
<?php
/*
*class GiraFixed

*Pretendo mostrar a possibilidade de girar uma figura de 90 em 90 graus
*Vc pode tambem pesquisar a biblioteca Gx is a php-gtk2 graphic library - Marc Quinton - june 2006.
*Pode tambem verificar o artigo 103 do site kksou
*Vou criar um visualizador e depois vc pode girar e ver o resultado no visualizador
*a imagem sempre sera salva com o outro nome escolhido
*lembre-se que n&#65533;o ocorre nenhum tratamento de imagem 
*Neste exemplo se a imagem tiver transparencia ou alfa ser&#65533; perdido,
*Neste artigo eu deixei sem alfa de proposito no proximo artigo eu mantenho
*
*Deveria utilizar a fun&#65533;&#65533;o imagerotate do php5 mas este deve ter sido compilado
*com a bliblioteca GD nativa o que n&#65533;o ocorre no ubuntu 8.04 e talvez em outros 
*e tambem nao esta no Php-gtk2b do Pablo para linux no windows n&#65533;o tentei
*
***Encapsula todo o exemplo do GiraFixed
*/

class GiraFixed
{   
    private 
$window;
    private 
$selected_file;
    private 
$row 300;
    private 
$col400;
    private 
$fixed;
   
    
/*
    *metodo construtor
    *cria a jnela principal
    */
    
public function __construct()
    {
        
$this->window = new GtkWindow();
        
$this->window->set_title('GiraFixed');
        
$this->window->set_size_request(800640);
        
$this->window->connect_simple('destroy', array('Gtk','main_quit'));
                
        
$vbox = new GtkVBox();
        
$button = new GtkButton('Rotate');
        
$button->set_size_request(-1,24);
        
$hbox = new GtkHBox();
        
$hbox->pack_start(new GtkLabel('Angle: '), 00);
        
$angle = new GtkEntry('');
        
$angle->set_size_request(40, -1);
        
$endereco = new GtkEntry('');
        
$endereco->set_size_request(200, -1);
        
$button->connect('clicked',array($this'on_button'),$angle,$endereco);
        
$hbox->pack_start($angle00);
        
$hbox->pack_start(new GtkLabel('  '), 00);
        
$hbox->pack_start($button00);
        
$buttonabrir = new GtkButton('Buscar imagem');
        
$buttonabrir->set_size_request(-1,24);
        
        
        
$buttonabrir->connect_simple('clicked',array($this'on_busca_imagem'),$endereco);
        
$buttonver = new GtkButton('Renderizar');
        
$buttonver->set_size_request(-1,24);
        
$buttonver->connect_simple('clicked',array($this'on_ver'),$endereco);
        
$hbox->pack_start($buttonabrir00);
        
$hbox->pack_start($endereco00);
        
$hbox->pack_start($buttonver00);
        
$vbox->pack_start($hbox00);
        
$this->fixed = new GtkFixed;
        
$vbox->pack_start($this->fixed);
        
$this->img=GtkImage::new_from_file($img_file);
        
$this->fixed->put($this->img,$this->col$this->row);
        
$this->window->add($vbox);
        
$this->window->show_all();
        
    }
    

    function 
on_button($button$angle_widget,$endereco) {
        
$angle $angle_widget->get_text(); // le o angulo de rota&#65533;&#65533;o
        //echo "angulo $angle";
        
$img_file=$endereco->get_text();
        list(
$img_width,$img_height$img_type) = getimagesize($img_file); 
        
//echo "img_size = $img_width x $img_height ($img_type)
";
        $tam_x= $img_width;
        $tam_y= $img_height;
        switch($img_type) { 
            case 1: $img = imagecreatefromgif($img_file); break;
            case 2: $img = imagecreatefromjpeg($img_file); break;
            case 3: $img = $this->LoadPNG($img_file); break;
            default: echo "
unsupported file format
"; exit(1);
        }
        $img2=$this->image_rotate($img, $angle,0x000000);
        
        //$img2 = imagerotate($img, -$angle, 0, 0);//funcao original depende de GD

        switch($img_type) { 
         case 1: imagegif($img2, "
imagengirada.gif"); break;
        case 2: imagejpeg($img2, "
imagengirada.jpg"); break;
        case 3: imagepng($img2, "
imagengirada.png"); break;
        }
        
        $dialog = new GtkDialog("
image rotate at $angle deg", null, Gtk::DIALOG_NO_SEPARATOR); // place the rotated image in a dialog

        $ext = end(explode('.',$img_file));
        $img = GtkImage::new_from_file("
imagengirada.$ext"); 
        $dialog->vbox->pack_start($img);
        $dialog->show_all();
    }
    function image_rotate($src_img, $angle,$corpreencher=0x000000)
    {
        
        $src_x = imagesx($src_img);
        $src_y = imagesy($src_img);
        echo"
 
tamx$scr_x tamy$scr_y angulo=$angle 
";
        if ($angle == 180)
        {
            $dest_x = $src_x;
            $dest_y = $src_y;
        }
        elseif (($angle == 90) || ($angle == 270))
        {
            $dest_x = $src_y;
            $dest_y = $src_x;
        }
        else
        {
            return $src_img;
        }
       
        $rotate=imagecreatetruecolor($dest_x,$dest_y);
        imagealphablending($rotate, false);
              
        switch ($angle)
        {
            case 270:
                $dest_x--;
                for ($y = 0; $y < $src_y; $y++)
                    for ($x = 0; $x < $src_x; $x++)
                        imagesetpixel($rotate, $dest_x - $y, $x, imagecolorat($src_img, $x, $y));
                break;
            case 90:
                $dest_y--;
                for ($y = 0; $y < $src_y; $y++)
                    for ($x = 0; $x < $src_x; $x++)
                        imagesetpixel($rotate, $y, $dest_y - $x, imagecolorat($src_img, $x, $y));
                break;
            case 180:
                echo"
 
tamx=$scr_x tamy=$scr_y angulo=$angle 
";
                $dest_x--;
                $dest_y;
                for ($y = 0; $y < $src_y; $y++)
                    for ($x = 0; $x < $src_x; $x++){
                        imagesetpixel($rotate, $dest_x - $x, $dest_y - $y, imagecolorat($src_img, $x, $y));
                        }
                break;
        }
        return $rotate;
    }
    function on_busca_imagem($endereco){
    $this->file_open();
    $endereco->set_text($this->selected_file);
    }    
    function file_open() {
        //global $dialog;
        $dialog = new GtkFileChooserDialog("
File Open", null,
            Gtk::FILE_CHOOSER_ACTION_OPEN,
            array(Gtk::STOCK_OK, Gtk::RESPONSE_OK), null);
        $hbox = new GtkHBox();
        $dialog->vbox->pack_start($hbox, 0, 0);
        $hbox->pack_start(new GtkLabel('File type:'), 0, 0);

        // create a combobox listing the available filter options
        $combobox = &GtkComboBoxEntry::new_text(); // note 1
        $combobox->append_text("
All Files");
        $combobox->append_text("
Text Files");
        $combobox->append_text("
HTML Files");
        $combobox->append_text("
PHP Files");
        $combobox->append_text("
Image Files");
        $combobox->get_child()->set_text('All Files');
        $combobox->connect('changed', 'on_change_filter'); // note 2
        
        $hbox->pack_start($combobox, 0, 0);

        $dialog->show_all();
        if ($dialog->run() == Gtk::RESPONSE_OK) {
            $this->selected_file = $dialog->get_filename(); // get the selected filename
            echo "
selected_file $this->selected_file
";
        }
        $dialog->destroy();
    }
    function on_ver($endereco)
    {
    $img_file=$endereco->get_text();
    $this->img->set_from_file($img_file); 
    }

    function LoadPNG($imgname) 
    {
        $im = @imagecreatefrompng($imgname); /* Attempt to open */
        if (!$im) { /* See if it failed */
            echo "
 
erro lendo o arquivo";
            $im  = imagecreatetruecolor(150, 30); /* Create a blank image */
            $bgc = imagecolorallocate($im, 255, 255, 255);
            $tc  = imagecolorallocate($im, 0, 0, 0);
            imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
            /* Output an errmsg */
            /*cria uma string com uma mensagem de erro*/
            imagestring($im, 1, 5, 5, "
Error loading $imgname", $tc);
        }
        return $im;

    }
     
}//fim da classe

// instancia a classe
new GiraFixed;
Gtk::Main();
?>

Imagem

Comentários

 Adicionar Comentário
 login
 Senha
 Título
 Comentário




PHP-GTK Brasil
PHP-GTK : Segunda Edição, um livro totalmente novo, abordando PHP5 e GTK2!!