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);
?>
Processamento de Imagem (GD)
- Introdução
- Instalação/Configuração
- Constantes pré-definidas
- Exemplos
- Funções da GD
- gd_info — Obtém informações sobre a biblioteca GD instalada atualmente
- getimagesize — Obtém o tamanho de uma imagem
- image_type_to_extension — Get file extension for image type
- image_type_to_mime_type — Obtém o Mime-Type para um tipo de imagem retornado por getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
- image2wbmp — Envia uma imagem para o browser ou arquivo
- imagealphablending — Set the blending mode for an image
- imageantialias — Indica se as funções de antialias devem ser usadas ou não
- imagearc — Desenha um elipse parcial
- imagechar — Desenha um caractere horizontalmente
- imagecharup — Desenha um caractere verticalmente
- imagecolorallocate — Aloca uma cor para uma imagem
- imagecolorallocatealpha — Aloca cor para uma imagem
- imagecolorat — Retorna o índice da cor de um pixel
- imagecolorclosest — Retorna o índice da cor mais próxima da cor especificada
- imagecolorclosestalpha — Retorna o índice da cor mais próxima da cor especificada + transparencia
- imagecolorclosesthwb — Get the index of the color which has the hue, white and blackness
- imagecolordeallocate — Desaloca uma cor para uma imagem
- imagecolorexact — Retorna o índice da cor especificada
- imagecolorexactalpha — Retorna o índice da cor especificada + transparencia
- imagecolormatch — Faz com que a versão das cores da paleta sejam mais próximas da versão truecolor
- imagecolorresolve — Retorna o índice da cor especificada ou a alternativa mais próxima possível
- imagecolorresolvealpha — Retorna o índice da cor especificada + transparência ou a sua alternativa mais próxima
- imagecolorset — Set the color for the specified palette index
- imagecolorsforindex — Retorna as cores de um índice
- imagecolorstotal — Retorna o número de cores na paleta de uma imagem
- imagecolortransparent — Define uma cor como tansparente
- imageconvolution — Apply a 3x3 convolution matrix, using coefficient and offset
- imagecopy — Copia parte de uma imagem
- imagecopymerge — Copia e combina uma parte de uma imagem
- imagecopymergegray — Copy and merge part of an image with gray scale
- imagecopyresampled — Copy and resize part of an image with resampling
- imagecopyresized — Copy and resize part of an image
- imagecreate — Cria uma nova imagem baseada em paleta
- imagecreatefromgd2 — Cria uma nova imagem apartir de um arquivo GD2 ou URL
- imagecreatefromgd2part — Cria uma nova imagem apartir de uma parte de um arquivo GD ou URL
- imagecreatefromgd — Cria uma nova imagem apartir de um arquivo GD ou URL
- imagecreatefromgif — Cria uma nova imagem a partir de um arquivo ou URL
- imagecreatefromjpeg — Cria uma nova imagem a a partir de um arquivo ou URL
- imagecreatefrompng — Cria uma nova imagem a apratir de um arquivo ou URL
- imagecreatefromstring — Cria uma nova imagem a apartir da imagem na string
- imagecreatefromwbmp — Cria uma nova imagem a apratir de um arquivo ou URL
- imagecreatefromxbm — Cria uma nova imagem a a partir de um arquivo ou URL
- imagecreatefromxpm — Cria uma nova imagem a apratir de um arquivo ou URL
- imagecreatetruecolor — Cria uma nova imagem true color
- imagedashedline — Desenha uma linha pontilhada
- imagedestroy — Destrói uma imagem
- imageellipse — Desenha um elipse
- imagefill — Flood fill
- imagefilledarc — Draw a partial arc and fill it
- imagefilledellipse — Desenha um elipse prenchido
- imagefilledpolygon — Desenha um poligono prenchido
- imagefilledrectangle — Desenha um retângulo prenchido
- imagefilltoborder — Flood fill to specific color
- imagefilter — Applies a filter to an image
- imagefontheight — Retorna a altura da fonte
- imagefontwidth — Retorna a largura da fonte
- imageftbbox — Give the bounding box of a text using fonts via freetype2
- imagefttext — Escreve texto na imagem usando fontes FreeType 2
- imagegammacorrect — Apply a gamma correction to a GD image
- imagegd2 — Envia uma imagem GD2
- imagegd — Envia a imagem GD para o browser ou um arquivo
- imagegif — Envia uma imagem para o browser ou arquivo
- imagegrabscreen — Captures the whole screen
- imagegrabwindow — Captures a window
- imageinterlace — Ativa ou desativa o entrelaçamento
- imageistruecolor — Indica quando uma imagem é uma imagem truecolor
- imagejpeg — Envia a imagem para o borwser ou arquivo
- imagelayereffect — Set the alpha blending flag to use the bundled libgd layering effects
- imageline — Desenha uma linha
- imageloadfont — Carrega uma nova fonte
- imagepalettecopy — Copia a paleta de uma imagem para a outra
- imagepng — Envia uma imagem PNG para o browser ou para um arquivo
- imagepolygon — Desenha um poligono
- imagepsbbox — Give the bounding box of a text rectangle using PostScript Type1 fonts
- imagepsencodefont — Change the character encoding vector of a font
- imagepsextendfont — Extend or condense a font
- imagepsfreefont — Libera a memória usada por uma fonte PostScript Type
- imagepsloadfont — Carrega uma fonte PostScript Type 1 a partir de um arquivo
- imagepsslantfont — Slant a font
- imagepstext — Draws a text over an image using PostScript Type1 fonts
- imagerectangle — Desenha um retângulo
- imagerotate — Gira uma imagem com o ângulo dado
- imagesavealpha — Define a opção para salvar a informação completa do alpha channel (ao invés de a transparencia de uma cor só) quando estiver salvando imagens PNG.
- imagesetbrush — Set the brush image for line drawing
- imagesetpixel — Define um único pixel
- imagesetstyle — Set the style for line drawing
- imagesetthickness — Define a espessura para o desenho de linhas
- imagesettile — Set the tile image for filling
- imagestring — Desenha uma string horizontalmente
- imagestringup — Desenha uma string verticalmente
- imagesx — Obtem a largura da imagem
- imagesy — Obtém a altura da imagem
- imagetruecolortopalette — Converte uma imagem true color para uma imagem de paleta
- imagettfbbox — Retorna uma caixa com o limites de um texto usando fontes TrueType
- imagettftext — Escreve texto na imagem usando fontes TrueType
- imagetypes — Retorna os tipos de imagens suportados por esta instalação do PHP
- imagewbmp — Envia uma imagem para o browser ou arquivo
- imagexbm — Output XBM image to browser or file
- iptcembed — Embute dados binários IPTC em uma imagem JPEG
- iptcparse — Analisa um bloco binário IPTC em tags simples.
- jpeg2wbmp — Converte um arquivo de imagem JPEG para um arquivo de imagem WBMP
- png2wbmp — Converte um arquivo de imagem PNG para um arquivo de imagem WBMP
GD
jordan at jkdesign dot org
07-Sep-2009 08:09
07-Sep-2009 08:09
scurvysquid at yahoo dot com
04-May-2009 05:08
04-May-2009 05:08
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.
Thomas
10-Dec-2008 08:05
10-Dec-2008 08:05
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.
code at ashleyhunt dot co dot uk
23-Oct-2008 11:02
23-Oct-2008 11:02
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
