When using GD, please make sure of the following things:
1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php
Procesamiento de imágenes y GD
- Introducción
- Instalación/Configuración
- Constantes predefinidas
- Ejemplos
- Funciones de GD e Imágenes
- gd_info — Reúne información acerca de la biblioteca GD instalada actualmente
- getimagesize — Obtiene el tamaño de una imagen
- getimagesizefromstring — Obtener el tamaño de una imagen desde una cadena
- image_type_to_extension — Obtiene la extensión de un tipo de imagen
- image_type_to_mime_type — Obtiene el tipo Mime de un tipo de imagen devuelto por getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
- image2wbmp — Exportar la imagen al navegador o a un fichero
- imageaffine — Return an image containing the affine tramsformed src image, using an optional clipping area
- imageaffinematrixconcat — Concat two matrices (as in doing many ops in one go)
- imageaffinematrixget — Return an image containing the affine tramsformed src image, using an optional clipping area
- imagealphablending — Establece el modo de mezcla para una imagen
- imageantialias — Permite o no el uso de funciones antialias
- imagearc — Dibujar un arco
- imagechar — Dibujar un carácter horizontalmente
- imagecharup — Dibujar un carácter verticalmente
- imagecolorallocate — Asigna un color para una imagen
- imagecolorallocatealpha — Asigna un color para una imagen
- imagecolorat — Obtener el índice del color de un píxel
- imagecolorclosest — Obtener el índice del color más próximo al color especificado
- imagecolorclosestalpha — Obtener el índice del color más próximo al color + alpha especificado
- imagecolorclosesthwb — Obtener el índice del color que tiene el tono, blancura y negrura
- imagecolordeallocate — Desasignar un color de una imagen
- imagecolorexact — Obtener el índice del color especificado
- imagecolorexactalpha — Obtener el índice del color + alpha especificado
- imagecolormatch — Hacer que los colores de la versión de la paleta de una imagen coincidan más estrechamente con la versión de color verdadero
- imagecolorresolve — Obtener el índice del color especificado o su alternativa más próxima posible
- imagecolorresolvealpha — Obtener el índice del color + alpha especificado o su alternativa más próxima posible
- imagecolorset — Establecer el color para el índice de paleta especificada
- imagecolorsforindex — Obtener los colores de un índice
- imagecolorstotal — Averiguar el número de colores de la paleta de una imagen
- imagecolortransparent — Definir un color como transparente
- imageconvolution — Aplicar una matriz de convolución de 3x3, usando coeficiente e índice
- imagecopy — Copiar parte de una imagen
- imagecopymerge — Copiar y fusionar parte de una imagen
- imagecopymergegray — Copiar y fusionar parte de una imagen con escala de grises
- imagecopyresampled — Copia y cambia el tamaño de parte de una imagen redimensionándola
- imagecopyresized — Copia y cambia el tamaño de parte de una imagen
- imagecreate — Crea una nueva imagen basada en paleta
- imagecreatefromgd2 — Crear una imagen nueva desde un archivo GD2 o una URL
- imagecreatefromgd2part — Crear una nueva imagen desde una parte dada de un archivo GD2 o una URL
- imagecreatefromgd — Crear una imagen nueva desde un archivo GD o una URL
- imagecreatefromgif — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefromjpeg — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefrompng — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefromstring — Crear una imagen nueva desde el flujo de imagen de la cadena
- imagecreatefromwbmp — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefromwebp — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefromxbm — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatefromxpm — Crea una nueva imagen a partir de un fichero o de una URL
- imagecreatetruecolor — Crear una nueva imagen de color verdadero
- imagecrop — Crop an image using the given coordinates and size, x, y, width and height
- imagecropauto — Crop an image automatically using one of the available modes
- imagedashedline — Dibujar una línea discontinua
- imagedestroy — Destruir una imagen
- imageellipse — Dibujar una elipse
- imagefill — Rellenar
- imagefilledarc — Dibujar un arco parcial y rellenarlo
- imagefilledellipse — Dibujar una elipse con relleno
- imagefilledpolygon — Dibujar un polígono con relleno
- imagefilledrectangle — Dibujar un rectángulo con relleno
- imagefilltoborder — Rellenar con un color específico
- imagefilter — Aplica un filtro a una imagen
- imageflip — Flips an image using a given mode
- imagefontheight — Obtener el alto de la fuente
- imagefontwidth — Obtener el ancho de la fuente
- imageftbbox — Devolver la caja circundante de un texto usando fuentes mediante FreeType 2
- imagefttext — Escribir texto en la imagen usando fuentes mediante FreeType 2
- imagegammacorrect — Aplicar una corrección gamma a la imagen GD
- imagegd2 — Imprime una imagen GD2 a un navegador o archivo
- imagegd — Imprime una imagen GD2 a un navegador o archivo
- imagegif — Exportar la imagen al navegador o a un fichero
- imagegrabscreen — Capturar la pantalla completa
- imagegrabwindow — Capturar una ventana
- imageinterlace — Habilitar o deshabilitar en entrelazamiento
- imageistruecolor — Averiguar si una imagen es de color verdadero
- imagejpeg — Exportar la imagen al navegador o a un fichero
- imagelayereffect — Establecer la bandera de mezcla alfa para usar los efectos de capa de la biblioteca gd incluida
- imageline — Dibujar una línea
- imageloadfont — Cargar una nueva fuente
- imagepalettecopy — Copiar la paleta de una imagen a otra
- imagepalettetotruecolor — Convierte una imagen basada en paleta a color verdadero
- imagepng — Imprimir una imagen PNG al navegador o a un archivo
- imagepolygon — Dibujar un polígono
- imagepsbbox — Devolver la caja circundante de un rectángulo de texto usando fuentes PostScript Type1
- imagepsencodefont — Cambiar el vector de codificación del caráter de una fuente
- imagepsextendfont — Extender o condensar una fuente
- imagepsfreefont — Liberar la memoria usada por una fuente PostScript Type 1
- imagepsloadfont — Cargar una fuente PostScript Type 1 desde un archivo
- imagepsslantfont — Inclinar una fuente
- imagepstext — Dibujar un texto sobre una imagen usando fuentes PostScript Type1
- imagerectangle — Dibuja un rectángulo
- imagerotate — Rotar una imagen con un ángulo dado
- imagesavealpha — Establecer la bandera para guardar la información completa del canal alfa (como oposición a la transparencia de un simple color) cuando se guardan imágenes PNG
- imagescale — Scale an image using the given new width and height
- imagesetbrush — Establecer la imagen de pincel para el dibujo de líneas
- imagesetinterpolation — Establecer el método de interpolación
- imagesetpixel — Establecer un simple píxel
- imagesetstyle — Establecer el estilo para el dibujo de líneas
- imagesetthickness — Establecer el grosor para el dibujo de líneas
- imagesettile — Establecer la imagen de tesela para rellenos
- imagestring — Dibujar una cadena horizontalmente
- imagestringup — Dibujar una cadena verticalmente
- imagesx — Obtener el ancho de una imagen
- imagesy — Obtener el alto de una imagen
- imagetruecolortopalette — Convertir una imagen de color verdadero en una imagen de paleta
- imagettfbbox — Devuelve la caja circundante de un texto usando fuentes TrueType
- imagettftext — Escribir texto en la imagen usando fuentes TrueType
- imagetypes — Devolver los tipos de imagen soportados por la versión actual de PHP
- imagewbmp — Exportar la imagen al navegador o a un fichero
- imagewebp — Imprimer una imagen WebP al navegador o fichero
- imagexbm — Imprimir una imagen XBM al navegador o a una archivo
- iptcembed — Incluir información IPTC binaria en una imagen JPEG
- iptcparse — Conviertir un bloque IPTC binario en simples etiquetas
- jpeg2wbmp — Convertir un archiov de imagen JPEG a un archivo de imagen WBMP
- png2wbmp — Convertir un archivo de imagen PNG a un archivo de imagen WBMP
kurdtpage at gmail dot com ¶
2 years ago
Thomas ¶
4 years ago
You know, maybe this goes without saying, but I thought I would drop a note in here. When developing code to resize images, it is best not to use GD. When using the current GD methodologies, you are reading content from an image and manipulating it. By then writing that content to a brand new file, you are losing the EXIF data.
For purposes when you want to retain EXIF data, it is recommended that you compile in and use the PECL Imagick extension. It has great resizing methods built right in and the EXIF data is retained.
herbert dot walde at googlemail dot com ¶
1 year ago
In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng().
And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.
Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.
Here is the full solution:
<?php
if(headers_sent()){
die('Headers have been send somewhere within my script');
}
ob_clean(); //Clears the buffer
header('Content-type: image/png');
imagepng($img, NULL, 0, NULL);
ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>
donatj at gmail dot com ¶
1 year ago
UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.
code at ashleyhunt dot co dot uk ¶
4 years ago
I have been looking to send the output from GD to a text string without proxying via a file or to a browser.
I have come up with a solution.
This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()
See the example below
<?php
// Create a test source image for this example
$im = imagecreatetruecolor(300, 50);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($im, NULL, 85);
// capture output to string
$contents = ob_get_contents();
// end capture
ob_end_clean();
// be tidy; free up memory
imagedestroy($im);
// lastly (for the example) we are writing the string to a file
$fh = fopen("./temp/img.jpg", "a+" );
fwrite( $fh, $contents );
fclose( $fh );
?>
Enjoy!
Ashley
rmayo100 at yahoo dot com ¶
3 years ago
I use GD to create graphs of data that exists in my system. I use a link like this to place the graph image on my page:
<img src="image.php" name="Image">
And this works just fine. Image.php acquires the data to be graphed and creates a png image with it. (And is even able to do it very quickly.)
However, I would also like to have external access that data. Unfortunately, it's is acquired by the graphing function from a UDP broadcast stream and I have no idea how to make it available outside that file (or how to capture it twice, perhaps).
I've had exactly no luck trying to implement a global variable, I suspect, because global variables really aren't global and their scope doesn't span multiple files.
I don't know if this is the right venue for this post, but I'm stumped so far and I had to post it somewhere.
Thanks,
R.
mail at ecross dot nl ¶
3 years ago
hello there,
i made a function to create a gradient image.
description:
gradient(int image_width, int image_height,
int start_red, int start_green, int start_blue,
int end_red, int end_green, int end_blue,
bool vertical)
function:
<?php
function gradient($image_width, $image_height,$c1_r, $c1_g, $c1_b, $c2_r, $c2_g, $c2_b, $vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;
// create a image
$image = imagecreatetruecolor($image_width, $image_height);
// make the gradient
for($i=0; $i<$image_height; $i++)
{
$color_r = floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g = floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b = floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;
$color = ImageColorAllocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}
# Prints out all the figures and picture and frees memory
header('Content-type: image/png');
if($vertical){$image = imagerotate($image, 90, 0);}
ImagePNG($image);
imagedestroy($image);
}
?>
jordan at jkdesign dot org ¶
3 years ago
Building on Ashley's example, here's an example of some code that grabs an existing image file and outputs an html img tag with the contents. I found it useful because I needed to not broadcast the filenames.
<?php
$file = 'images/01.png';
$image = imagecreatefrompng($file);
imagealphablending($image, false);
imagesavealpha($image, true);
// start buffering
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/png;base64,".base64_encode($contents)."' />";
imagedestroy($image);
?>
mac_doggie at hotmail dot com ¶
2 years ago
A way to read the color of a pixel:
<?php
$img = imagecreatefrompng("image1.png");
$w = imagesx($img);
$h = imagesy($img);
for($y=0;$y<$h;$y++) {
for($x=0;$x<$w;$x++) {
$rgb = imagecolorat($img, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
echo "#".str_repeat("0",2-strlen(dechex($r))).dechex($r).
str_repeat("0",2-strlen(dechex($g))).dechex($g).
str_repeat("0",2-strlen(dechex($b))).dechex($b).",";
}
echo "<br />\r\n";
}
?>
[EDIT BY thiago: merged two notes from same submitter.]
scurvysquid at yahoo dot com ¶
4 years ago
to address Thomas' note about exif data, exif is only valid for .tiff and .jpg files. As always, it's up to the individual to make the call but I personally would prefer to create an abstraction layer to work for all images, and relying on exif data means you need to limit your allowed image types. I've heard some great things about the GD library and found them to all be true in my own use of it, losing the nominally useful data specific to jpegs and pngs is not a sufficient reason alone to convince me to use imagemagick instead.
