PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

imagegrabscreen> <imagegd
Last updated: Fri, 05 Sep 2008

view this page in

imagegif

(PHP 4, PHP 5)

imagegifOutput image to browser or file

Description

bool imagegif ( resource $image [, string $filename ] )

imagegif() creates the GIF file in filename from the image image . The image argument is the return from the imagecreate() or imagecreatefrom* function.

The image format will be GIF87a unless the image has been made transparent with imagecolortransparent(), in which case the image format will be GIF89a.

Parameters

image

An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

filename

The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 Outputting an image using imagegif()

<?php
// Create a new image instance
$im imagecreatetruecolor(100100);

// Make the background white
imagefilledrectangle($im0099990xFFFFFF);

// Draw a text string on the image
imagestring($im34020'GD Library'0xFFBA00);

// Output the image to browser
header('Content-type: image/gif');

imagegif($im);
imagedestroy($im);
?>

Example #2 Converting a PNG image to GIF using imagegif()

<?php

// Load the PNG
$png imagecreatefrompng('./php.png');

// Save the image as a GIF
imagegif($png'./php.gif');

// Free from memory
imagedestroy($png);

// We're done
echo 'Converted PNG image to GIF with success!';
?>

Notes

Note: Since all GIF support was removed from the GD library in version 1.6, this function is not available if you are using that version of the GD library. Support is expected to return in a version subsequent to the rerelease of GIF support in the GD library in mid 2004. For more information, see the » GD Project site.
The following code snippet allows you to write more portable PHP applications by auto-detecting the type of GD support which is available. Replace the sequence header ("Content-type: image/gif"); imagegif ($im); by the more flexible sequence:

<?php
// Create a new image instance
$im imagecreatetruecolor(100100);

// Do some image operations here

// Handle output
if(function_exists('imagegif'))
{
    
// For GIF
    
header('Content-type: image/gif');

    
imagegif($im);
}
elseif(
function_exists('imagejpeg'))
{
    
// For JPEG
    
header('Content-type: image/jpeg');

    
imagejpeg($imNULL100);
}
elseif(
function_exists('imagepng'))
{
    
// For PNG
    
header('Content-type: image/png');

    
imagepng($im);
}
elseif(
function_exists('imagewbmp'))
{
    
// For WBMP
    
header('Content-type: image/vnd.wap.wbmp');

    
imagewbmp($im);
}
else
{
    
imagedestroy($im);

    die(
'No image support in this PHP server');
}

// If image support was found for one of these
// formats, then free it from memory
if($im)
{
    
imagedestroy($im);
}
?>

Note: As of PHP 3.0.18 and 4.0.2 you can use the function imagetypes() in place of function_exists() for checking the presence of the various supported image formats:

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



imagegrabscreen> <imagegd
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
imagegif
stefan at colulus dot com
30-May-2008 03:18
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.

code:

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

<?php
//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
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// 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
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

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

?>
mogmios at gmail dot com
19-May-2008 07:06
Simple function for converting a PNG to a GIF. Seems to work for me.

function png2gif ( $image_in, $image_out ) {
 $img = imagecreatefrompng ( $image_in );
 $trans_color = imagecolortransparent ( $img );
 $trans_index = imagecolorallocate ( $img, $trans_color['red'], $trans_color['green'], $trans_color['blue'] );
 imagecolortransparent ( $img, $trans_index );
 imagegif ( $img, $image_out );
 return True;
}
serhio_forever at yahoo dot com
13-Feb-2008 12:24
Note that when converting some transparent png to a gif image , it won't be transparent , don't know why...

from gif to png works fine with :
    $img = imagecreatefromgif($name);

    $x = imageSX($img);
    $y = imageSY($img);
    $new_img = ImageCreateTrueColor($x, $y);
    imagealphablending($new_img, false);
    $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
    imagefill($new_img, 0, 0, $colorTransparent);
    imagesavealpha($new_img, true);
    imagepng($new_img, $dest, 5);
alan hogan dot com slash contact
12-Nov-2007 08:47
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:
http://www.php.net/manual/en/function.imagecolorat.php
rokfaith at gmail dot com
14-Aug-2006 10:33
I've recieved e-mails on this, so i will elaborate (original post ~2 posts down):
the RenderFrame($frame) function should be a function that returns an image resource and does something sensibe with the integer (frame number) that it gets passed.

function RenderFrame($frame) {
  $im = imagecreatetruecolor(100,100); //or just imagecreate for smaller images
  imageantialias($im, true); //works only on true color images, slower
  //draw something on image (imageline, imagerect, imageftt...)
  return $im;
}

this way the image is drawn and destroyed every iteration of the loop, so you can animate moving things, eg. text. if you keep the image between function calls, you get the effect of progressively drawing the image:
change
   $im = imagecreatetruecolor(100,100);
into
  static $im = imagecreatetruecolor(100,100);
2ge at 2ge dot us
13-Aug-2006 06:02
Hello,

there is many guides how to make animated gif (with or without temp files), but I found this really nice solution, it uses no patched GD, no external utils, just pure PHP. Look into http://www.phpclasses.org/browse/package/3163.html

Hope this helps.
rokfaith at gmail dot com
06-Jul-2006 07:34
to create an animated gif with gifsicle, but without storing temporary images on disk:
<?
$cmd = '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)) {
  die('Unable to start gifsicle');
}
for ($frame=0; $frame<$total_frames; $frame++) {
  $image = RenderFrame($frame);
  ob_start();
  imagegif($image);
  fwrite($pipes[0], ob_get_contents());
  ob_end_clean();
  imagedestroy($image);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
?>

just define $outfile and RenderFrame(), and that's it.
joconoco at yahoo dot com
03-Feb-2006 10:12
i havent worked with it, yet. but for the discussion about animated gifs, this might help, too:
http://ffmpeg-php.sourceforge.net/apidoc.php
fieldy
31-Jan-2006 08:54
For using the new animated gif functions of gd you can build in some functions in php. I took the patch from http://hyvatti.iki.fi/~jaakko/sw/. But it's a patch on php 5.0.2. I made it on php 5.1.2.
On http://www.linuxforhomies.be/view_artikel.jsp?id=10 you can see how to do it. Sorry that it's in dutch, but I think it's understandable.

It adds following functions:
int imagegifanimbegin(int im [, string filename [, int GlobalColormap [, int Loops]]]);
int imagegifanimadd(int im [, string filename [, int LocalColormap [, LeftOfs [, int TopOfs [, int Delay [, int Disposal [, int previm]]]]]]]);
int imagegifanimend([string filename]);
cascade at mylifesucks dot de
29-Nov-2005 09:02
I would rather use gifsicle ( http://www.lcdf.org/gifsicle/ ) instead of convert. It runs much faster with big animations. I got large animations with over 500 frames rendered where convert was killed by my system because of memory consumption. And it contains pretty well optimization.

A sample gifsicle usage (not much optimized):
<?
// Sample gifsicle usage to create a scrolling text

$gifsicle = "/usr/local/bin/gifsicle"; # http://www.lcdf.org/gifsicle/
$time = time();
for ($rend_frame = 0; $rend_frame <= 26; $rend_frame++) {
    $im = @imagecreatetruecolor(300, 20);
    $background = imagecolorallocate($im, 0, 0, 100);
    $red = imagecolorallocate($im, 255, 0, 0);
    $filename = "/tmp/giftest_".$time."_".str_pad($rend_frame, 10, "0", STR_PAD_LEFT).".gif";
    $framefiles[] = $filename;
    imagestring($im, 3, ($rend_frame * 15)-80, 3, "Animation rox", $red);
    imagegif($im,$filename);
    imagedestroy($im);
};
$outfile = "/tmp/giftest_".$time.".gif";
$cmd = "$gifsicle --loop -O1 --delay 25 /tmp/giftest_".$time."*> $outfile";
exec($cmd, $out, $err);
foreach ($framefiles as $framefile) {
    if (file_exists($framefile)) unlink($framefile);
};
header('Content-type: image/gif');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: inline; filename=test.gif');
header('Content-Length: '.@filesize($outfile));
readfile($outfile);
unlink($outfile);
?>

Or get patches from http://hyvatti.iki.fi/~jaakko/sw/ to be able to do it all inside php...
Leigh Purdie
03-Jul-2005 09:17
Simple animated-gif hack (requires ImageMagick):

<html><body>
<?php
        $icount
=0;
        for(
$count=0;$count<40;$count++) {
               
$im=imagecreate(200,200);
               
imagecolorallocate($im,0,0,255);
               
$white=imagecolorallocate($im,255,255,255);
               
imagerectangle($im,$count,$count,200-$count,200-$count,$white);
               
$icount++;
               
$tcount=sprintf("%04d",$icount);
               
imagegif($im,"/tmp/test-$tcount.gif");
               
imagedestroy($im);
        }
       
exec("/usr/bin/convert -delay 2 -loop 10 /tmp/test*.gif /var/www/html/Tests/Test-Anim.gif");
?>
<img src="/Tests/Test-Anim.gif">
</body>
</html>
Lauri Harpf
23-Jun-2005 01:25
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.
jemore at nospam dot m6net dot fr
22-Nov-2003 03:24
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.
tom et lenderlab dit com
05-Dec-2002 06:08
The rgb2gif utility included in giflib can be used for fast and easy gif output with any version of GD
http://ietpd1.sowi.uni-mainz.de/cgi-bin/man2html?rgb2gif

use either the rgboutput or the rgboutput_truecolor functions, depending on your GD version/style of image you're working with:

<?
$x=40;
$y=40;

//make a simple image with some text
$im = imagecreate($x, $y);
$bg = imagecolorallocate($im, 0,0,0);
      imagefill($im, 0,0, $bg);

$red=imagecolorallocate($im, 255, 0, 0);
    imagestring($im, 1, 2, 8, "testing", $red);

//output the 24 bit rgb-formatted image to file
$f = fopen("image.rgb", "w");
fwrite($f, rgboutput($im));
imagedestroy($im);

//load that file into rgb2gif and capture the output
$status = `rgb2gif -1 -s $x $y image.rgb`;
$f = fopen("test.gif", "w");
fwrite($f, $status);

function rgboutput($im) {
    $x = imagesx($im);
    $y = imagesy($im);
    $output="";
    for($i=0;$i<$y;$i++) {
        for($j=0;$j<$x;$j++) {
            $c=ImageColorAt($im, $j, $i);
            $c = imagecolorsforindex($im, $c);
            $c = array_map("chr", $c);
            $output.=$c['red'].$c['green'].$c['blue'];
        }
    }
    return $output;
}

function rgboutput_truecolor($im) {
    $x = imagesx($im);
    $y = imagesy($im);
    $output="";
    for($i=0;$i<$y;$i++) {
        for($j=0;$j<$x;$j++) {
            $rgb=ImageColorAt($im, $j, $i);
            $r = chr(($rgb >> 16) & 0xFF);
            $g = chr(($rgb >> 8) & 0xFF);
            $b = chr($rgb & 0xFF);
            $output.=$r.$g.$b;
        }
    }
    return $output;
}
?><img src="test.gif">
polone at townnews dot com
03-Apr-2002 04:40
read also RFC2557: http://www.ietf.org/rfc/rfc2557.txt
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.
kremlin at home dot com
27-Feb-2001 02:45
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
david at hooshla dot com
28-Apr-2000 11:45
This is how you load and display an image file:

<?
Header("Content-Type: image/gif");
$fn=fopen("./imagefile.gif","r");
fpassthru($fn);
?>

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

imagegrabscreen> <imagegd
Last updated: Fri, 05 Sep 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites