libreria instalar extension ext php gd

instalar - php 7.2 ext gd



Cambiar el tamaño con GD produce imágenes en negro (4)

Asegúrate de que gd esté instalado y habilitado.

Para verificar, cree un archivo PHP con este comando:

<?php phpinfo();

Acceda al archivo a través de un navegador y desplácese hacia abajo hasta la sección gd. Si gd no está allí, o está deshabilitado, agréguelo con yum, apt-get o el equivalente de Windows.

También necesita la biblioteca GD disponible ( http://www.libgd.org/ ).

Considere cambiar a IMagick ( http://php.net/manual/en/book.imagick.php ) para obtener una mejor calidad de imagen.

¿Qué puede hacer que php gd produzca una imagen negra después de cambiar el tamaño? El siguiente código siempre genera una imagen en negro para cada archivo jpeg válido.

<?php $filename = ''test.jpg''; $percent = 0.5; header(''Content-Type: image/jpeg''); list($width, $height) = getimagesize($filename); $newwidth = $width * $percent; $newheight = $height * $percent; $thumb = imagecreatetruecolor($newwidth, $newheight); $source = imagecreatefromjpeg($filename); imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); imagejpeg($thumb); imagedestroy($thumb); ?>

salida de gd_info() :

Array ( [GD Version] => bundled (2.1.0 compatible) [FreeType Support] => 1 [FreeType Linkage] => with freetype [T1Lib Support] => [GIF Read Support] => 1 [GIF Create Support] => 1 [JPEG Support] => 1 [PNG Support] => 1 [WBMP Support] => 1 [XPM Support] => [XBM Support] => 1 [JIS-mapped Japanese Font Support] => )

El código apareció trabajando en otros entornos. ¿Probablemente está relacionado con el sistema operativo, los paquetes instalados, las bibliotecas, etc.?


Intente este código para ver los errores que están ocurriendo:

<?php error_reporting(E_ALL); ini_set("display_errors", 1); $filename = ''test.jpg''; $percent = 0.5; list($width, $height) = getimagesize($filename); $newwidth = $width * $percent; $newheight = $height * $percent; $thumb = imagecreatetruecolor($newwidth, $newheight); $source = imagecreatefromjpeg($filename); imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); //header(''Content-Type: image/jpeg''); //imagejpeg($thumb); //imagedestroy($thumb); ?>

Por lo tanto, si PHP encuentra un error, lo mostrará en la pantalla. Si no hay ningún error, la pantalla se mostrará en blanco.


La siguiente función crea una miniatura, con pocos cambios también puede O / P en la pantalla. Creo que de esta manera es más útil.

/* * PHP function to resize an image maintaining aspect ratio * http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html * * Creates a resized (e.g. thumbnail, small, medium, large) * version of an image file and saves it as another file */ define(''THUMBNAIL_IMAGE_MAX_WIDTH'', 150); define(''THUMBNAIL_IMAGE_MAX_HEIGHT'', 150); function generate_image_thumbnail($source_image_path, $thumbnail_image_path) { list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path); switch ($source_image_type) { case IMAGETYPE_GIF: $source_gd_image = imagecreatefromgif($source_image_path); break; case IMAGETYPE_JPEG: $source_gd_image = imagecreatefromjpeg($source_image_path); break; case IMAGETYPE_PNG: $source_gd_image = imagecreatefrompng($source_image_path); break; } if ($source_gd_image === false) { return false; } $source_aspect_ratio = $source_image_width / $source_image_height; $thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT; if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) { $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) { $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio); $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT; } else { $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH; $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio); } $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height); imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height); imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90); imagedestroy($source_gd_image); imagedestroy($thumbnail_gd_image); return true; }

Consulte esta más información.

Si php-gd no existe use el siguiente comando.

sudo apt-get install php5-gd


Investigación

Solo trato de reproducir tu situación. Ejecutar su código con PHP listo para usar y Apache muestra lo siguiente

La imagen " http://localhost/ " no se puede mostrar porque contiene errores.

Aunque el navegador le dice que hubo algunos errores, no se pueden ver debido a que los encabezados devueltos en respuesta fueron de Content-Type: image/jpeg lo que obliga al navegador a interpretarlo como una imagen. Al eliminar el header y configurar lo siguiente se generarán errores.

ini_set(''error_reporting'', E_ALL); ini_set(''display_errors'', true); ... //header(''Content-Type: image/jpeg''); ... Responder

¿Qué puede hacer que php gd produzca una imagen negra después de cambiar el tamaño?

Dado que la salida de gd_info prueba que la extensión GD está cargada, verifique si el nombre del archivo (linux es sensible a mayúsculas y minúsculas) y los permisos son correctos. Si Apache se ejecuta como www-data (grupo)

sudo chown :www-data test.jpg && sudo chmod 660 test.jpg Mejora de código / solución

ini_set(''error_reporting'', E_ALL); ini_set(''display_errors'', true); if (extension_loaded(''gd'') && function_exists(''gd_info'')) { $filename = ''test.jpg''; if (file_exists($filename) && is_readable($filename)) { $percent = 0.5; header(''Content-Type: image/jpeg''); list($width, $height) = getimagesize($filename); $newwidth = $width * $percent; $newheight = $height * $percent; $thumb = imagecreatetruecolor($newwidth, $newheight); $source = imagecreatefromjpeg($filename); imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); imagejpeg($thumb); imagedestroy($thumb); } else { trigger_error(''File or permission problems''); } } else { trigger_error(''GD extension not loaded''); } Comentarios

Esto debería ser usado como una solución temporal (entorno de desarrollo). En mi humilde opinión, los errores deben ser manejados por un controlador central de errores, display_errors debe ser false en la producción. Además, los errores (en este caso, sería un Fatal error ) se registran de forma predeterminada: compruebe los registros para obtener más información (cuanto más frecuente, mejor). Además, en linux (con apt ) one-liner instalará GD en su sistema:

sudo apt-get update && sudo apt-get install php5-gd && sudo /etc/init.d/apache2 restart