2011-04-16 8 views
18

Estoy usando una secuencia de comandos que permite a los usuarios subir imágenes. El script cambia el tamaño y convierte las imágenes a JPEG.Cómo reemplazar el fondo negro con blanco al redimensionar/convertir imágenes PNG con fondos transparentes a JPEG.

El problema que tengo es cuando se carga un PNG con transparencia, la imagen JPEG resultante es negra donde había transparencia.

¿Cómo puedo editar el siguiente script para reemplazar el negro con el blanco? Ya hace esto para GIF pero no para PNG.

// RESIZE IMAGE AND PUT IN USER DIRECTORY 
    switch($this->file_ext) 
{ 
    case "gif": 
     $file = imagecreatetruecolor($width, $height); 
     $new = imagecreatefromgif($this->file_tempname); 
     $kek=imagecolorallocate($file, 255, 255, 255); 
     imagefill($file,0,0,$kek); 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 

    case "bmp": 
     $file = imagecreatetruecolor($width, $height); 
     $new = $this->imagecreatefrombmp($this->file_tempname); 
     for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 

    case "jpeg": 
    case "jpg": 
     $file = imagecreatetruecolor($width, $height); 
     $new = imagecreatefromjpeg($this->file_tempname); 
     for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 

    case "png": 
     $file = imagecreatetruecolor($width, $height); 
     $new = imagecreatefrompng($this->file_tempname); 
     for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 
    } 

    chmod($photo_dest, 0777); 

    return true; 
} 

traté de editar el caso "PNG": parte para que coincida con la de la caso "gif": código pero el JPEG resultante es completamente blanco.

ACTUALIZACIÓN:

me fijo yo mismo.

¡Gracias a todos por contribuir!

que sustituyen:

case "png": 
     $file = imagecreatetruecolor($width, $height); 
     $new = imagecreatefrompng($this->file_tempname); 
     for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 

con:

case "png": 
     $file = imagecreatetruecolor($width, $height); 
     $new = imagecreatefrompng($this->file_tempname); 
     $kek=imagecolorallocate($file, 255, 255, 255); 
     imagefill($file,0,0,$kek); 
     imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
     imagejpeg($file, $photo_dest, 100); 
     ImageDestroy($new); 
     ImageDestroy($file); 
     break; 
+0

¿Qué hace este imagecolorallocate? Está recibiendo 4 parámetros para png, ¿no debería recibir 5, para el canal alfa? – Andre

+0

No escribí el código, soy un novato. No sé la respuesta a tu pregunta. Lamento no poder ayudarte a ayudarme. – Jeff

+0

Todo esto está en el manual, en realidad. _imagecolorallocate - Devuelve un identificador de color que representa el color compuesto por los componentes RGB dados. _ Y para la transparencia alfa, debe usar 'imagecolorallocatealpha', que de hecho agrega un quinto parámetro: http://php.net/manual/en/ function.imagecolorallocatealpha.php – kasimir

Respuesta

0

Ok, esta función es de php. Como nunca he trabajado con imágenes en php, entonces no lo sabía.

Por lo tanto, las imágenes se componen de tres colores: RGB (rojo, verde, azul). En caso de PNG, también se compone de otro filtro, llamado alfa, que es la transparencia

SO, sólo para PNG, debe cambiar imagecolorallocate-imagecolorallocatealpha($file,$i,$i,$i,$i);

Esto hará que sus imágenes transparentes. ¿Esto resuelve su problema o realmente los necesita en fondo blanco?

Edit: También noté que está utilizando la función imagejpg en todos los casos. Cambiar a la función correspondiente, es decir, imagepng, imagebmp, imagegif

+0

Necesito mantener imagejpeg para todas las funciones porque todas las imágenes nuevas deben ser jpg. Hice los otros cambios que sugirió pero los jpg resultantes todavía tienen negro donde había transparencia. No necesito mantener la transparencia, solo necesito cambiar el negro a blanco. ¡Gracias! – Jeff

0

Trate como esto (no probado):

case "png": 
    $file = imagecreatetruecolor($width, $height); 
    $new = imagecreatefrompng($this->file_tempname); 
    imagefilledrectangle ($file, 0, 0, $width, $height, imagecolorallocate($file, 0,0,0)) 

(predraw un fondo blanco imagen de archivo $ sucesivamente)

Además, el for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } parte se ve extraño.

+0

Gracias pero no funcionó. – Jeff

0
switch($image_extension){ 
    case 'gif': 
    case 'GIF': 
    $image_orig_resource = imagecreatefromgif($image_orig_path); 
    break; 
    case 'png': 
    case 'PNG': 
    $image_orig_resource = imagecreatefrompng($image_orig_path); 
    break; 
    case 'jpg': 
    case 'jpeg': 
    case 'JPG': 
    case 'JPEG': 
    $image_orig_resource = imagecreatefromjpeg($image_orig_path); 
    break; 
    default: 
    throw new Exception('Extension not supported'); 
} 

$image_resource = imagecreatetruecolor($width, $height); 
imagefill($image_resource, 0, 0, imagecolorallocate($image_resource, 255, 255, 255)); // white background; 

imagecopyresampled($image_resource, $image_orig_resource, 0, 0, 0, 0, $width, $height, $image_orig_width, $image_orig_height); 

imagejpeg($image_resource, $image_path, 100); // quality: [0-100] 
0

Después imagen de color verdadero añadir las líneas:

$file = imagecreatetruecolor($width, $height); 
    $background = imagecolorallocate($file, 0, 0, 0); 
    imagecolortransparent($file, $background); 
    imagealphablending($file, false); 
    imagesavealpha($file, true); 

Esto ayudará en mailtaining alfa para todos los formatos. Haga ping si no obtiene respuesta.

Cuestiones relacionadas