导航首页 » 技术教程 » PHP:imagegif()的用法_GD库图像处理函数
PHP:imagegif()的用法_GD库图像处理函数 157 2023-12-15   

imagegif

(PHP 4, PHP 5)

imagegif — 输出图象到浏览器或文件。

说明

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

imagegif()image 图像以 filename 为文件名创建一个 GIF 图像。image 参数是 imagecreate() 或 imagecreatefrom* 函数的返回值。

图像格式为 GIF87a。如果用了 imagecolortransparent() 使图像为透明,则其格式为 GIF89a。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的图象资源。

filename

文件保存的路径,如果未设置或为 NULL,将会直接输出原始图象流。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

范例

Example #1 使用 imagegif() 输出一个图像

<?php
// 创建新的图像实例
$im = imagecreatetruecolor(100, 100);

// 设置背景为白色
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);

//在图像上写字
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);

// 输出图像到浏览器
header('Content-Type: image/gif');

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

Example #2 使用 imagegif() 将一个 PNG 转换成 GIF

<?php

// 载入 PNG
$png = imagecreatefrompng('./php.png');

// 以 GIF 保存图像
imagegif($png, './php.gif');

// 释放内存
imagedestroy($png);

// 完工
echo 'Converted PNG image to GIF with success!';
?>

注释

Note:

不过从 GD 库 1.6 起所有的 GIF 支持都移除了,并在版本 2.0.28 中加了回来。如果使用这些 版本之间的 GD 库时本函数不可用。 更多信息见 » GD Project 站点。

以下代码段通过自动检测 GD 支持的图像类型来写出移植性更好的 PHP 程序。用更灵活的代码替代了原来的 header("Content-type: image/gif"); imagegif($im);:

<?php
// 创建新的图像实例
$im = imagecreatetruecolor(100, 100);

// 在这里对图像进行一些操作

// 处理输出
if(function_exists('imagegif'))
{
    // 针对 GIF
    header('Content-Type: image/gif');

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

    imagejpeg($im, NULL, 100);
}
elseif(function_exists('imagepng'))
{
    // 针对 PNG
    header('Content-Type: image/png');

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

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

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

// 如果发现图像是以上的格式之一,就从内存中释放
if($im)
{
    imagedestroy($im);
}
?>

Note:

自 PHP 3.0.18 和 4.0.2 起可以用 imagetypes() 函数代替 function_exists() 来检查是否支持某种图像格式:

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

参见

imagepng() - 以 PNG 格式将图像输出到浏览器或文件 imagewbmp() - 以 WBMP 格式将图像输出到浏览器或文件 imagejpeg() - 输出图象到浏览器或文件。 imagetypes() - 返回当前 PHP 版本所支持的图像类型


!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103