Foros del Web » Programando para Internet » PHP »

subir imagen png con fondo transparente

Estas en el tema de subir imagen png con fondo transparente en el foro de PHP en Foros del Web. hola tengo el siguiente codigo el cual me permite cargar imagenes en cualquier formato y lo he ido modificando poco a poco con el tiempo ...
  #1 (permalink)  
Antiguo 25/10/2016, 16:28
 
Fecha de Ingreso: febrero-2010
Ubicación: valencia
Mensajes: 146
Antigüedad: 14 años, 2 meses
Puntos: 3
subir imagen png con fondo transparente

hola tengo el siguiente codigo el cual me permite cargar imagenes en cualquier formato y lo he ido modificando poco a poco con el tiempo para crear distintos tamaños de la imagen cargada

Tengo el siguiente problema cuando cargo una imagen png con fondo transparente me la crea con fondo negro y todas las demas copias en distintos tamaños tambien

con la gif la original se sube con fondo transparente pero todas las demas se crean con fondo negro


necesito subir la imagen con fondo transparente


Código PHP:

<?php

 
class ModifiedImage{
    private 
$_image;
    private 
$_imageType;
    private 
$_transparent;
    private 
$_validExtensions = array(
        
IMAGETYPE_JPEG => 'image/jpeg',
        
IMAGETYPE_GIF => 'image/gif',
        
IMAGETYPE_PNG => 'image/png',
    ); 
 
    private function 
_imagecopymerge_alpha($dst_im$src_im$dst_x$dst_y$src_x$src_y$src_w$src_h$pct){
        
$cut imagecreatetruecolor($src_w$src_h);
        
imagecopy($cut$dst_im00$dst_x$dst_y$src_w$src_h);
        
imagecopy($cut$src_im00$src_x$src_y$src_w$src_h);
        
imagecopymerge($dst_im$cut$dst_x$dst_y00$src_w$src_h$pct);
    }
 
    private function 
_setPositionWatermark($width$height$position 'bottom right'$paddingH 10$paddingV 10)
    {
        switch(
strtolower($position)){
            case 
'top left':
                
$h $paddingH;
                
$v $paddingV;
                break;
            case 
'top center':
                
$h = ($this->getWidth() / 2) - ($width 2) - $paddingH;
                
$v $paddingV;
                break;
            case 
'top right':
                
$h $this->getWidth() - $width $paddingH;
                
$v $paddingV;
                break;
            case 
'middle left':
                
$h $paddingH;
                
$v = ($this->getHeight() / 2) - ($height 2) - $paddingV;
                break;
            case 
'middle center':
                
$h = ($this->getWidth() / 2) - ($width 2) - $paddingH;
                
$v = ($this->getHeight() / 2) - ($height 2) - $paddingV;
                break;
            case 
'middle right':
                
$h $this->getWidth() - $width $paddingH;
                
$v = ($this->getHeight() / 2) - ($height 2) - $paddingV;
                break;
            case 
'bottom left':
                
$h $paddingH;
                
$v $this->getHeight() - $height $paddingV;
                break;
            case 
'bottom center':
                
$h = ($this->getWidth() / 2) - ($width 2) - $paddingH;
                
$v $this->getHeight() - $height $paddingV;
                break;
            default:
                
$h $this->getWidth() - $width $paddingH;
                
$v $this->getHeight() - $height $paddingV;
        }
        return array(
'horizontal'=>$h'vertical'=>$v);
    }
 
    public function 
__construct($fileName=null$transparent=false)
    {
        
$this->setTransparent($transparent);
 
        if(!
is_null($fileName)){
            
$this->load($fileName);
        }
    }
 
    public function 
setTransparent($bool)
    {
        
$this->_transparent = (boolean)$bool;
    }
 
    public function 
getImageType() 
    {
        return 
array_key_exists($this->_imageType$this->_validExtensions)
            ? 
$this->_validExtensions[$this->_imageType]
            : 
null;
    }
 
    public function 
isValidExtension() 
    {
        return 
array_key_exists($this->_imageType$this->_validExtensions)
            ? 
true
            
'Invalid extension, you can upload only ' implode(', '$this->_validExtensions);
    }
 
    public function 
load($fileName)
    {
        
$imageInfo getimagesize($fileName);
        
$this->_imageType $imageInfo[2];
 
        if(
$this->_imageType == IMAGETYPE_JPEG){
            
$this->_image imagecreatefromjpeg($fileName);
        }
        else if(
$this->_imageType == IMAGETYPE_GIF){
            
$this->_image imagecreatefromgif($fileName);
        }
        else if(
$this->_imageType == IMAGETYPE_PNG){
            
$this->_image imagecreatefrompng($fileName);
        }
    }
 
    public function 
save($fileName$compression 100$permissions null)
    {
        if(
$this->_imageType == IMAGETYPE_JPEG){
            
imagejpeg($this->_image$fileName$compression);
        }
        else if(
$this->_imageType == IMAGETYPE_GIF){
            
imagegif($this->_image$fileName);
        }
        else if(
$this->_imageType == IMAGETYPE_PNG){
            
imagepng($this->_image$fileName);
        }
 
        if(!
is_null($permissions)) {
            
chmod($fileName$permissions);
        }
    }
 
    public function 
output()
    {
        
// TODO: Agregar encabezados según el tipo de imagen
        
if($this->_imageType == IMAGETYPE_JPEG){
            
imagejpeg($this->_image);
        }
        else if(
$this->_imageType == IMAGETYPE_GIF){
            
imagegif($this->_image);
        }
        else if(
$this->_imageType == IMAGETYPE_PNG){
            
imagepng($this->_image);
        }
    }
 
    public function 
getWidth()
    {
        return 
imagesx($this->_image);
    }
 
    public function 
getHeight()
    {
        return 
imagesy($this->_image);
    }
 
    public function 
resizeToHeight($height)
    {
        
$ratio $height $this->getHeight();
        
$width $this->getWidth() * $ratio;
        
$this->resize($width,$height);
    }
 
    public function 
resizeToWidth($width)
    {
        
$ratio $width $this->getWidth();
        
$height $this->getHeight() * $ratio;
        
$this->resize($width$height);
    }
 
    public function 
scale($scale)
    {
        
$width $this->getWidth() * $scale 100;
        
$height $this->getHeight() * $scale 100;
        
$this->resize($width$height);
    }
 
    public function 
resize($width$height)
    {
        
$newImage imagecreatetruecolor($width$height);
        if(
$this->_imageType == IMAGETYPE_PNG && $this->_transparent === true){
            
imagealphablending($newImagefalse);
            
imagesavealpha($newImagetrue);
            
imagefilledrectangle($newImage00$width$heightimagecolorallocatealpha($newImage255255255127));
        }
        else if(
$this->_imageType == IMAGETYPE_GIF && $this->_transparent === true){
            
$index imagecolortransparent($this->_image);
            if(
$index != -&& $index != 255){
                
$colors imagecolorsforindex($this->_image$index);
                
$transparent imagecolorallocatealpha($newImage$colors['red'], $colors['green'], $colors['blue'], $colors['alpha']);
                
imagefill($newImage00$transparent);
                
imagecolortransparent($newImage$transparent);
            }
        }
        
imagecopyresampled($newImage$this->_image0000$width$height$this->getWidth(), $this->getHeight());
        
$this->_image $newImage;
    }
    
    
/* -----------       FUNCION INVENTADA  PARA IMAGEN DE BANNER PROPORCIONADA   -------- */
    
    
    
public function resizeBanner($ruta,$ancho,$alto)
    {
    
            
$ruta;
            
$ancho;
            
$alto;
            
            
$width $this->getWidth();
            
$height $this->getHeight();
            
            
// se toma en cuenta la menor medida para acumularla en tamanodecorte
            
            
if ($width $height){ // si el alto es menor
            
$tamanodecorte $height;
            } else if (
$width <= $height){ // si el ancho es menor o igual
            
$tamanodecorte $width;
            }

            
$info_fuente    getimagesize($ruta);

            
$centro_x       round($info_fuente[0] / 2);
            
$centro_y       round($info_fuente[1] / 2);
            
$x_recorte      $centro_x - ($width 2);
            
$y_recorte      $centro_y - ($height 2);


            
$newImage  imagecreatetruecolor($ancho$alto); // tamaño en blanco del nuevo lienzo
            
            
            
            
            

            //  $x_recorte = centro de la imagen por el eje de las x
            //  $y_recorte = centro de la imagen por el eje de las y
            //    $ancho, $alto = tamaño de la nueva imagen por el eje de x y de y
            //  $tamanodecorte = tamaño a cortar de la imagen original x y  
            
            
            
imagecopyresampled($newImage$this->_image00$x_recorte$y_recorte$ancho$alto$this->getWidth(), $this->getHeight());
            
            
$this->_image $newImage;        
            
               
    }
    
    
    
    
/* -----------      FIN  FUNCION INVENTADA  PARA IMAGEN DE BANNER PROPORCIONADA   -------- */
  #2 (permalink)  
Antiguo 26/10/2016, 03:46
Avatar de gogupe  
Fecha de Ingreso: octubre-2006
Ubicación: Mallorca
Mensajes: 897
Antigüedad: 17 años, 5 meses
Puntos: 32
Respuesta: subir imagen png con fondo transparente

Hola, te paso el script que utilizo para los png con fondo transparente.

Código PHP:
                $tmp=imagecreatetruecolor($nuevo_ancho,$nuevo_alto);
                
$src=imagecreatefrompng($myfile["tmp_name"]);
                
imagealphablending($tmpfalse);
                
imagesavealpha($tmp,true);
                
$transparent imagecolorallocatealpha($tmp255255255127);
                
imagefilledrectangle($tmp00$nuevo_ancho$nuevo_alto$transparent);
                
imagecopyresampled($tmp$src0000$nuevo_ancho$nuevo_alto$ancho$alto);
                
imagepng($tmp$destino);
                
imagedestroy($tmp);
                
imagedestroy($src); 
Tendrás que sustituir los valores del alto y el ancho.

Cualquier duda, postea !!!
__________________
Somos una serie de acontecimiento que puede venir al caso en un momento dado.

Etiquetas: png
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 00:47.