(PHP 4, PHP 5, PHP 7, PHP 8)

imagegifEnvia uma imagem para o browser ou arquivo


imagegif(resource $image, string $filename = ?): bool

imagegif() cria um arquivo GIF em filename a partir da imagem image. O parâmetro image é o retorno da função imagecreate() ou imagecreatefrom*.

O formato da imagem será GIF87a a menos que a imagem tenha sido feita transparente com imagecolortransparent(), neste caso o formato da imagem será GIF89a.



Um objeto GdImage, retornado por uma das funções de criação de imagens, como imagecreatetruecolor().


O caminho para salvar o arquivo. Se não definido ou null, o stream da imagem será mostrado diretamente.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.



Já que todo o suporte GIF foi removido da biblioteca GD na versão 1.6, esta função não esta disponível se você esta usando esta versão da biblioteca GD. O suporte é esperado para retornar em uma versão subsequente ao lançamento do suporte GIF na biblioteca GD no meio de 2004. Para maiores informações veja o site do projeto » GD Project.

O seguinte pedaço de código permite a você criar aplicações PHP mais portáveis auto-detectando o tipo de suporte GD que esta disponível. Substitua a sequencia header ("Content-type: image/gif"); imagegif ($im); por uma sequencia mais flexível:

if (function_exists("imagegif")) {
header("Content-type: image/gif");
} elseif (
function_exists("imagejpeg")) {
header("Content-type: image/jpeg");
imagejpeg($im, "", 0.5);
} elseif (
function_exists("imagepng")) {
header("Content-type: image/png");
} elseif (
function_exists("imagewbmp")) {
header("Content-type: image/vnd.wap.wbmp");
} else {
"No image support in this PHP server");


A partir das versões 3.0.18 e 4.0.2 você pode usar a função imagetypes() no lugar de function_exists() para conferir a presença dos vários formatos de imagem suportados:

if (imagetypes() & IMG_GIF) {
header ("Content-type: image/gif");
imagegif ($im);
} elseif (
imagetypes() & IMG_JPG) {
/* ... etc. */

Veja Também

  • imagepng() - Emite uma imagem PNG para o navegador ou arquivo
  • imagewbmp() - Envia uma imagem para o browser ou arquivo
  • imagejpeg() - Envia a imagem para o borwser ou arquivo
  • imagetypes() - Retorna os tipos de imagens suportados por esta instalação do PHP

add a note

User Contributed Notes 12 notes

polone at townnews dot com
21 years ago
read also RFC2557:
For handling inline images in email.

I've been playing around with the "data" URL scheme as proposed by RFC 2397 which states how to perform inline, bas64 encoded images. A number of browsers support this format from some of my tests and would be an interesting way of removing overhead from multiple HTTP connections. Basically, the IMG tag would be:

<IMG SRC="/-/data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">

Something like that. Note also that I start the URI with "/-/" before the rest of the data scheme spec. If you don't start it with this, it won't work in a lot of the different browsers I tested (such as IE). Note this is useful for very small images only (as most browsers appear to have a limitation on the size of HTML element data of 1024). Browsers where this syntax worked that I tested are the following:

IE 6.x (windows)
Mozilla 0.97+ (linux)
Opera 5, 6 (windows)
Netscape 4.7+ (mac, windows)
IE 5 (macintosh)

This should work for other image types as well, such as PNG. JPEG files aren't really suggested (usually, these files are too large). BTW - there is no advantage to this method if the image will appear more than ONCE in the page because you will be transmitting the same data multiple times as opposed to just once (most browsers realize that already downloaded data that has multiple references only requires one HTTP call).

Consider using this method if you want to make a single PHP program that outputs both text and an image AND you want to make only on HTTP call. Cheers.
mail at ignore dot area dot nospam dot joshho dot com
11 years ago
apparently GD does not support animated GIFs.

instead, we're stuck with the old fashioned way:
('Content-Type: image/gif');
stefan at colulus dot com
15 years ago
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.


//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
"Image $next:<br>";
"<img src = 'Image.php?\$text=$next'>";

//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image

//returns completed image to calling script
Header('Content-Type: image/png');

rokfaith at gmail dot com
16 years ago
to create an animated gif with gifsicle, but without storing temporary images on disk:

= 'gifsicle --loop -O1 --multifile --delay 25 - > '.$outfile;
$desc = array(0 => array("pipe", "r"),1 => array("pipe", "w"),2 => array("pipe", "w"));
$proc = proc_open($cmd, $desc, $pipes);
if (!
is_resource($proc)) {
'Unable to start gifsicle');
for (
$frame=0; $frame<$total_frames; $frame++) {
$image = RenderFrame($frame);
fwrite($pipes[0], ob_get_contents());

just define $outfile and RenderFrame(), and that's it.
9 years ago
To keep GIF animation, you can try the class writing based on GD
GD Enhancer
kremlin at home dot com
22 years ago
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
jemore at nospam dot m6net dot fr
19 years ago
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
Lauri Harpf
17 years ago
Using <IMG SRC="image.php"> to dynamically generate images is a bit problematic regarding cache. Unless caching is activated, IE seems to get confused about the type of the image when attempting to save it. A .GIF created in the above way causes the browser to suggest saving the image with .BMP, not .GIF.

A solution is to activate cache with session_cache_limiter('public'); in "image.php", after which IE will correctly save as .GIF. If you do not want the cache to block any changes in the dynamic image, make sure that the SRC keeps changing with every reload. Something like "image.php/" . mt_rand(1,100000) . ".gif" seems to work well.

Might be trivial to some, but I spent a couple of hours figuring out why IE always wants to save my dynamic .GIF's as .BMP's.
grant k.
12 years ago
It should be noted that if you only want to "save" the file, and not display it to the browser, you should catch the imagegif into a variable.


//Only saves the file to a destination, no display

$image_value = imagegif($image, $save_file_to_path);

//Saves file and attempts to display it, but will throw an error message

imagegif($image, $save_file_to_path);
//Only displays, never saves as a file

//Note: In [my] third example, for displaying only, it is probably good to use the "header('Content-type: image/gif'); declaration, but it's not needed in the first example for saving as a .gif file.
Leigh Purdie
17 years ago
Simple animated-gif hack (requires ImageMagick):

$count=0;$count<40;$count++) {
exec("/usr/bin/convert -delay 2 -loop 10 /tmp/test*.gif /var/www/html/Tests/Test-Anim.gif");
<img src="/Tests/Test-Anim.gif">
alan hogan dot com slash contact
15 years ago
Note that you *can* save with a transparent color **and dither** using GD2.
For a useful example, see the png-to-gif function in my coment here:
david at hooshla dot com
23 years ago
This is how you load and display an image file:

("Content-Type: image/gif");

Note that there are no new-lines in the content type header.
To Top