PHP Doku:: Ausgabe des Bildes im Browser oder als Datei - function.imagegif.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzBildverarbeitung und -generierungBildbearbeitung und GDGD- und Image-Funktionenimagegif

Ein Service von Reinhard Neidl - Webprogrammierung.

GD- und Image-Funktionen

<<imagegd

imagegrabscreen>>

imagegif

(PHP 4, PHP 5)

imagegifAusgabe des Bildes im Browser oder als Datei

Beschreibung

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

imagegif() erzeugt eine GIF-Datei aus dem übergebenen image. Der Inhalt des Parameters image ist die Rückgabe der Funktionen imagecreate() oder imagecreatefrom*

Das Dateiformat wird GIF87a sein, es sei denn das Bild wurde mittels imagecolortransparent() transparent gemacht. In diesem Fall wird das Dateiformat GIF89a sein.

Parameter-Liste

image

Eine von den verschiedenen Erzeugungsfunktionen wie imagecreatetruecolor() gelieferte Grafikressource.

filename

Der Pfad der Datei, in die geschrieben werden soll. Wenn dies nicht gesetzt oder NULL ist, so wird die Bilddatei direkt ausgegeben.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Beispiel #1 Ein Bild mittels imagegif() ausgeben

<?php
// Erzeugt ein neues Bild
$im imagecreatetruecolor(100100);

// Den Hintergrund weiß machen
imagefilledrectangle($im0099990xFFFFFF);

// Einen Text im Bild ausgeben
imagestring($im34020'GD Library'0xFFBA00);

// Das Bild an den Browser ausgeben
header('Content-type: image/gif');

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

Beispiel #2 Eine PNG-Datei mit imagegif() in GIF konvertieren

<?php

// Die PNG-Datei laden
$png imagecreatefrompng('./php.png');

// Die Datei im GIF-Format speichern
imagegif($png'./php.gif');

// Den Speicher freigeben
imagedestroy($png);

// Wir sind fertig
echo 'Die PNG-Datei wurde erfolgreich nach GIF konvertiert!';
?>

Anmerkungen

Hinweis:

Die Unterstützung des GIF-Dateiformates wurde in der Version 1.6 der GD-Bibliothek entfernt und in der Version 2.0.28 wieder hinzugefügt. Nähere Angaben finden Sie auf der Webseite des » GD Projekts.

Der folgende Codeauszug erlaubt es Ihnen leichter umzuziehende PHP-Anwendungen zu schreiben, indem die von GD unterstützten Dateiformat automatisch erkannt werden. Ersetzen Sie den Abschnitt header ("Content-type: image/gif"); imagegif ($im); durch den folgenden Abschnitt:

<?php
// Ein neues Bild erzeugen
$im imagecreatetruecolor(100100);

// Hier wird das Bild bearbeitet

// Ausgabebehandlung
if(function_exists('imagegif'))
{
    
// Für GIF
    
header('Content-type: image/gif');

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

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

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

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

    die(
'Auf diesem Server gibt es keine unterstützten Bildformate');
}

// Falls Unterstützung für eines von diesen Formaten
// gefunden wurde, geben wir den Speicher frei
if($im)
{
    
imagedestroy($im);
}
?>

Hinweis:

Seit der PHP-Version 4.0.2 kann die Funktion imagetypes() anstelle der Funktiom function_exists() zur Prüfung der Unterstützung der verschiedenen Dateiformate verwendet werden:

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

Siehe auch

  • imagepng() - Ausgabe eines Bildes im Browser oder als Datei im PNG-Format
  • imagewbmp() - Output image to browser or file
  • imagejpeg() - Ausgabe des Bildes im Browser oder als Datei
  • imagetypes() - Gibt die von der aktuell verwendeten PHP-Version unterstützten Grafik-Formate zurück


12 BenutzerBeiträge:
- Beiträge aktualisieren...
grant k.
27.07.2010 19:46
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.

Example:

<?php
//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
imagegif($image);

//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.
?>
Kris dot Craig at gmail dot com
8.04.2010 16:07
This is a suggestion for people who are using the function not to pass a NULL value for the $filename argument, with a detailed explanation as to why as well as a suggested alternative.

It should be noted that, contrary to what the manual implies, an error will be returned if you specify a NULL filename instead of simply omitting it.

For example:

<?php
function Test( $img, $filename = NULL )
{
$ok = imagegif( $img, $filename );
}
?>

This will return an image that contains errors.  However, if you simply omit $filename altogether, you'll be just fine.

To make the above function work error-free, do this:

<?php
function Test( $img, $filename = NULL )
{
if (
$filename == NULL )
{
$ok = imagegif( $img );
}
else
{
$ok = imagegif( $img, $filename );
}
}
?>

The manual somewhat inaccurately states the following for the $filename argument:

"If not set or NULL, the raw image stream will be outputted directly."

In fact, as I just demonstrated, this is misleading as it fails to mention that passing it as a NULL value causes a broken (error) image to be displayed.

I would recommend you avoid this by simply making sure that you don't pass a NULL value for $filename.
stefan at colulus dot com
30.05.2008 20: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
20.05.2008 0:06
Simple function for converting a PNG to a GIF. Seems to work for me.

<?php
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;
}
?>
alan hogan dot com slash contact
12.11.2007 11: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
7.07.2006 0:34
to create an animated gif with gifsicle, but without storing temporary images on disk:

<?php
$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.
Leigh Purdie
4.07.2005 2: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.06.2005 18: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.11.2003 19: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.
polone at townnews dot com
3.04.2002 21: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.02.2001 6:45
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
david at hooshla dot com
29.04.2000 4:45
This is how you load and display an image file:

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

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



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)