Foros del Web » Programando para Internet » PHP »

Libreria GD: Problema con transparecias PNG

Estas en el tema de Libreria GD: Problema con transparecias PNG en el foro de PHP en Foros del Web. Hola a todos, estoy implementando una aplicacion para que genere el tiempo. El problema es que si intento poner iconos con transparencias a una imagen ...
  #1 (permalink)  
Antiguo 13/02/2008, 03:11
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Libreria GD: Problema con transparecias PNG

Hola a todos, estoy implementando una aplicacion para que genere el tiempo.

El problema es que si intento poner iconos con transparencias a una imagen con transparencias no funciona. (32 bits sobre 32 bits)

En cambio si pongo los iconos transparentes sobre una imagen sin transparencia funciona correctamente (32 bits sobre 24 bits)

Estoy utilizando php: version 5.2.3

Alguien conoce alguna alternativa o si las versiones nuevas de php5 ya lo soporta?

Muchas gracias, eskerrik asko.
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #2 (permalink)  
Antiguo 13/02/2008, 09:48
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: Libreria GD: Problema con transparecias PNG

¿Haz probado usar imagealphablending?

Saludos.
  #3 (permalink)  
Antiguo 14/02/2008, 01:39
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: Libreria GD: Problema con transparecias PNG

no tenia idea de la existencia de esa funcion, en breve hago las pruebas y lo comento ;)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #4 (permalink)  
Antiguo 14/02/2008, 02:08
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: Libreria GD: Problema con transparecias PNG

Pues no no funciona, de todas pondre el codigo para que veais como lo hace:

- Hay 2 XML, uno estatico y otro dinamico:
- XML estatico: Guarda las ID's y las posiciones X e Y de las ciudades
- XML dinamico: Guardar las ID's y el nombre del icono del tiempo.
- Imagen principal.
- El programa recorre el xml estatico y por cada ID recorre el XML dinamico y coge el valor del tiempo y pinta el icono del tiempo en las coordenadas correspondientes.

Estructura de directorio:

raiz: / : index.php y gd.module
img: /img : imagenes principales
icon: /img/icon : imagenes de los iconos del tiempo.
xml: /xml : ruta de los xml's
outpur: /output : path para los archivos generados.

index.php
Código PHP:
<?php
include("gd.module.php");

    
$date=date("Ymd"); // fecha de hoy
    
$a= new xml2img();
    
    
$a->staticXmlpath="xml/"//path xml estatico
    
$a->staticXmlfile="static.xml"// nombre xml estatico
    
$a->staticNodename="ciudad"// nombre del nodo en el xml estatico
    
    
$a->dinamicXmlpath="xml/"//path xml dinamico
    
$a->dinamicXmlfile="dinamic.xml"// nombre xml dinamico
    
$a->dinamicNodename="ciudad"// nombre del nodo en el xml dinamico    
    
    
$a->imgpath="img/"// path imagenes
    
$a->imgfile="mapa.png"// nombre imagen         
    
$a->iconpath="img/icon/"// path iconos
    
$a->iconext="png"// extension para los iconos
    
    
$a->savepath="output/"// path de salida
    
$a->filename="mapa".$date.".png"// nombre fichero salida
    
    
$a->XmlToImg(); // ejecutar transformacion
    
$a->Show(); // mostrar imagen    
?>
gd.module.php

Código PHP:
<?php
/*
 * 
 * Extensiones soportadas: png, jpeg, jpg, gif
 * 
 */
class xml2img
 
{
     public 
$staticXmlpath// path de los xml
     
public $staticXmlfile// nombre de fichero de los xml
     
public $staticNodename// nombre del nodo en el xml
     
     
public $dinamicXmlpath// path de los xml
     
public $dinamicXmlfile// nombre de fichero de los xml
     
public $dinamicNodename// nombre del nodo en el xml     
     
     
public $imgpath// path de las imagenes
     
public $imgfile// nombre de la imagen en la cual se dibujaran las demas
     
public $iconpath// path donde estaran los iconos
     
public $iconext// extension para los iconos
     
     
public $savepath// path donde se guardara la imagen
     
public $filename// nombre de la imagen    
     
     
private $img// imagen generada
     
     
public function XmlToImg()
      {                    
          if(@!
$staticxml=simplexml_load_file($this->staticXmlpath.$this->staticXmlfile)) // cargar xml
           
{
               echo 
"Failed loading: ".$this->staticXmlpath.$this->staticXmlfile." file.";
               return;
           }
          if(@!
$dinamicxml=simplexml_load_file($this->dinamicXmlpath.$this->dinamicXmlfile)) // cargar xml
           
{
               echo 
"Failed loading: ".$this->dinamicXmlpath.$this->dinamicXmlfile." file.";
               return;
           }           
          
$extension=$this->getExtension($this->imgpath.$this->imgfile);
          switch(
$extension)
           {
               case 
"png":
                  if(@!
$this->img=imagecreatefrompng($this->imgpath.$this->imgfile))    // cargar img
                   
{
                       echo 
"Failed loading: ".$this->imgpath.$this->imgfile." file.";
                       return;
                   }                          
                   break;
               case 
"jpg":
               case 
"jpeg":
                  if(@!
$this->img=imagecreatefromjpeg($this->imgpath.$this->imgfile))    // cargar img
                   
{
                       echo 
"Failed loading: ".$this->imgpath.$this->imgfile." file.";
                       return;
                   }               
                   break;
               case 
"gif":
                  if(@!
$this->img=imagecreatefromgif ($this->imgpath.$this->imgfile))    // cargar img
                   
{
                       echo 
"Failed loading: ".$this->imgpath.$this->imgfile." file.";
                       return;
                   }                 
                   break;
               default:
                   echo 
"Invalid Image type: ".$this->imgpath.$this->imgfile;
                   return;                   
           } 
          
imagealphablending($this->img,true);          
          
imagesavealpha($this->img,true);
        
// Recorrer XML
        
$tmpnode=$this->staticNodename;
          foreach(
$staticxml->$tmpnode as $node
          {    
              
$xmlarray['id']=$node['id'];              
              
$xmlarray['x']=$node['x'];
              
$xmlarray['y']=$node['y'];
              
$xmlarray['icon']=$this->getIcon($node['id'],$dinamicxml);
              
$this->img=$this->PasteIcon($this->img,$xmlarray);
              unset(
$xmlarray);
          }          
         
// Copiar imagen generada en el path indicado
         
if(!imagepng($this->img,$this->savepath.$this->filename))
          {
              echo 
"Failed copying generated image ".$this->filename."in ".$this->savepath;
          }
      } 
     
// funcion para obtener extension
     
private function getExtension($file)
      {
          return 
strtolower(substr(strrchr($file,"."),1,strlen(strrchr($file,"."))));
      }
     
// funcion para recorren el xml en busca del icono
     
private function getIcon($id,$dinamicxml)
      {
          
$tmpnode=$this->dinamicNodename;
          foreach(
$dinamicxml->$tmpnode as $node
          {    
              if(
$node['id']=="$id")
               {
                   return 
$node['icon'];
               }              
          }                  
      }
     
// funcion para pegar el icono en la imagen
     
private function PasteIcon($img,$xmlarray)
      {                                        
              
$this->iconext=strtolower($this->iconext);
              
$icon=$this->iconpath.$xmlarray['icon'].".".$this->iconext;
              
$size=getimagesize($icon);                                  
               switch(
$this->iconext)
                {
                    case 
"png":
                      if(@!
$icon=imagecreatefrompng($icon))    // cargar icono
                       
{
                           echo 
"Failed getting icon image ".$xmlarray['icon'].$this->icoext;
                           return;
                       }                          
                       break;                         
                    case 
"jpg":
                    case 
"jpeg":
                      if(@!
$icon=imagecreatefromjpeg($icon))    // cargar icono
                       
{
                           echo 
"Failed getting icon image ".$xmlarray['icon'].$this->icoext;
                           return;
                       }                    
                        break;
                    case 
"gif":
                      if(@!
$icon=imagecreatefromgif($icon))    // cargar icono
                       
{
                           echo 
"Failed getting icon image ".$xmlarray['icon'].$this->icoext;
                           return;
                       }                    
                        break;
                    default:
                        echo 
"Failed getting icon image ".$xmlarray['icon'].$this->icoext;
                        return;
                        break;
                }          
               
imagecopy($img,$icon,$xmlarray['x'],$xmlarray['y'],0,0,$size[0],$size[1]);
               
imagedestroy($icon);
               return 
$img;           
      }
     public function 
Show()
      {
          
$tmpext=$this->getExtension($this->imgfile);
          
header('Cache-Control: no-store, no-cache, must-revalidate');
          
header("Content-Type: image/".$tmpext);
          
$tmpimg=imagepng($this->img);
          echo 
$tmpimg;     
          
destroy($tmpimg);      
      }
 }
?>
antes de recorrer el xml hago un

Código PHP:
imagealphablending($this->img,true); 
pero no funciona :(

Edito se me olvido poner los XML:

static.xml
Código:
<?xml version="1.0" encoding="utf-8"?>
<static>
	<ciudad id="1" x="90" y="35" es="La Coruña" gl="A Coruña"/>
	<ciudad id="2" x="145" y="80" es="Lugo" gl="Lugo"/>
	<ciudad id="3" x="50" y="125" es="Pontevedra" gl="Pontevedra"/>
	<ciudad id="4" x="105" y="150" es="Orense" gl="Ourense"/>
</static>
dinamic.xml
Código:
<?xml version="1.0" encoding="utf-8"?>
<dinamic>
	<ciudad id="1" icon="iconoCubierto"/>
	<ciudad id="2" icon="iconoChubascos"/>
	<ciudad id="3" icon="iconoDespejado"/>
	<ciudad id="4" icon="iconoGranizo"/>
</dinamic>
vamos que habra en la carpeta icons:

- iconoCubierto.png
- iconoChubascos.png
- iconoDespejado.png
- iconoGranizo.png
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan

Última edición por ZiTAL; 14/02/2008 a las 10:08
  #5 (permalink)  
Antiguo 14/02/2008, 09:24
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: Libreria GD: Problema con transparecias PNG

Mmm según entiendo tienes que usar imagealphablending en todas las imágenes, en las dos que vayas a copiar y en la resultante...

Saludos.
  #6 (permalink)  
Antiguo 14/02/2008, 09:58
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: Libreria GD: Problema con transparecias PNG

He puesto el:
Código PHP:
imagealphablending($this->img,true); 
despues del createfrom*

y el :

Código PHP:
imagealphablending($icon,true); 
en la funcion PaseIcon

pero no funciona.

Incluso lo he puesto antes de que ejecutar el imagepng para la imagen resultante, pero nada.

No se, no le veo sentido el porque no se pueda hacer.
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #7 (permalink)  
Antiguo 14/02/2008, 10:05
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: Libreria GD: Problema con transparecias PNG

Estas seguro que los canales alpha de las dos imágenes están bien?, la verdad no se porque no funciona, yo he utilizado mucho imagealphablending para preservar el canal alpha y no había tenido problemas.

Saludos.
  #8 (permalink)  
Antiguo 14/02/2008, 10:09
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: Libreria GD: Problema con transparecias PNG

Solucionado, el truco estaba aqui:

Código PHP:
...
          
imagealphablending($this->img,true);          
          
imagesavealpha($this->img,true);
... 
Si no hay savealpha NO WAY ;)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #9 (permalink)  
Antiguo 14/02/2008, 10:54
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
Re: Libreria GD: Problema con transparecias PNG

GatorV no se, con imagesavealpha funciona correctamente, lo dejare asi.

Aqui el ejemplo funcionando:

http://zital.no-ip.org/gd/index.php

Para descargar el codigo fuente:

http://zital.no-ip.org/gd/gd.tar.bz2

;)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
  #10 (permalink)  
Antiguo 14/02/2008, 11:40
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: Libreria GD: Problema con transparecias PNG

Me da gusto ver que ya funciona, y que haz dejado el ejemplo para que todos lo vean.

Saludos.
  #11 (permalink)  
Antiguo 14/02/2008, 11:54
Avatar de ZiTAL  
Fecha de Ingreso: marzo-2004
Ubicación: Bermio (Bizkaia)
Mensajes: 1.545
Antigüedad: 20 años, 1 mes
Puntos: 62
De acuerdo Re: Libreria GD: Problema con transparecias PNG

De nada hombre, al final ha quedado chulo eh ;)
__________________
http://zital.no-ip.org
____________________

Euskerie ahuen eta bijotzan
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 18:09.