文字

图像处理和 GD

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 范例
    • 使用 PHP 创建 PNG 图像
    • 使用 Alpha 通道为图像加水印
    • 使用 imagecopymerge 函数创建半透明水印
  • GD 和图像处理 函数
    • gd_info — 取得当前安装的 GD 库的信息
    • getimagesize — 取得图像大小
    • getimagesizefromstring — 从字符串中获取图像尺寸信息
    • image_type_to_extension — 取得图像类型的文件后缀
    • image_type_to_mime_type — 取得 getimagesize,exif_read_data,exif_thumbnail,exif_imagetype 所返回的图像类型的 MIME 类型
    • image2wbmp — 以 WBMP 格式将图像输出到浏览器或文件
    • imageaffine — 返回经过仿射变换后的图像,剪切区域可选
    • imageaffinematrixconcat — Concat two matrices (as in doing many ops in one go)
    • imageaffinematrixget — Return an image containing the affine tramsformed src image, using an optional clipping area
    • imagealphablending — 设定图像的混色模式
    • imageantialias — 是否使用抗锯齿(antialias)功能
    • imagearc — 画椭圆弧
    • imagechar — 水平地画一个字符
    • imagecharup — 垂直地画一个字符
    • imagecolorallocate — 为一幅图像分配颜色
    • imagecolorallocatealpha — 为一幅图像分配颜色 + alpha
    • imagecolorat — 取得某像素的颜色索引值
    • imagecolorclosest — 取得与指定的颜色最接近的颜色的索引值
    • imagecolorclosestalpha — 取得与指定的颜色加透明度最接近的颜色
    • imagecolorclosesthwb — 取得与给定颜色最接近的色度的黑白色的索引
    • imagecolordeallocate — 取消图像颜色的分配
    • imagecolorexact — 取得指定颜色的索引值
    • imagecolorexactalpha — 取得指定的颜色加透明度的索引值
    • imagecolormatch — 使一个图像中调色板版本的颜色与真彩色版本更能匹配
    • imagecolorresolve — 取得指定颜色的索引值或有可能得到的最接近的替代值
    • imagecolorresolvealpha — 取得指定颜色 + alpha 的索引值或有可能得到的最接近的替代值
    • imagecolorset — 给指定调色板索引设定颜色
    • imagecolorsforindex — 取得某索引的颜色
    • imagecolorstotal — 取得一幅图像的调色板中颜色的数目
    • imagecolortransparent — 将某个颜色定义为透明色
    • imageconvolution — 用系数 div 和 offset 申请一个 3x3 的卷积矩阵
    • imagecopy — 拷贝图像的一部分
    • imagecopymerge — 拷贝并合并图像的一部分
    • imagecopymergegray — 用灰度拷贝并合并图像的一部分
    • imagecopyresampled — 重采样拷贝部分图像并调整大小
    • imagecopyresized — 拷贝部分图像并调整大小
    • imagecreate — 新建一个基于调色板的图像
    • imagecreatefromgd2 — 从 GD2 文件或 URL 新建一图像
    • imagecreatefromgd2part — 从给定的 GD2 文件或 URL 中的部分新建一图像
    • imagecreatefromgd — 从 GD 文件或 URL 新建一图像
    • imagecreatefromgif — 由文件或 URL 创建一个新图象。
    • imagecreatefromjpeg — 由文件或 URL 创建一个新图象。
    • imagecreatefrompng — 由文件或 URL 创建一个新图象。
    • imagecreatefromstring — 从字符串中的图像流新建一图像
    • imagecreatefromwbmp — 由文件或 URL 创建一个新图象。
    • imagecreatefromwebp — 由文件或 URL 创建一个新图象。
    • imagecreatefromxbm — 由文件或 URL 创建一个新图象。
    • imagecreatefromxpm — 由文件或 URL 创建一个新图象。
    • imagecreatetruecolor — 新建一个真彩色图像
    • imagecrop — Crop an image using the given coordinates and size, x, y, width and height
    • imagecropauto — Crop an image automatically using one of the available modes
    • imagedashedline — 画一虚线
    • imagedestroy — 销毁一图像
    • imageellipse — 画一个椭圆
    • imagefill — 区域填充
    • imagefilledarc — 画一椭圆弧且填充
    • imagefilledellipse — 画一椭圆并填充
    • imagefilledpolygon — 画一多边形并填充
    • imagefilledrectangle — 画一矩形并填充
    • imagefilltoborder — 区域填充到指定颜色的边界为止
    • imagefilter — 对图像使用过滤器
    • imageflip — Flips an image using a given mode
    • imagefontheight — 取得字体高度
    • imagefontwidth — 取得字体宽度
    • imageftbbox — 给出一个使用 FreeType 2 字体的文本框
    • imagefttext — 使用 FreeType 2 字体将文本写入图像
    • imagegammacorrect — 对 GD 图像应用 gamma 修正
    • imagegd2 — 将 GD2 图像输出到浏览器或文件
    • imagegd — 将 GD 图像输出到浏览器或文件
    • imagegif — 输出图象到浏览器或文件。
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • imageinterlace — 激活或禁止隔行扫描
    • imageistruecolor — 检查图像是否为真彩色图像
    • imagejpeg — 输出图象到浏览器或文件。
    • imagelayereffect — 设定 alpha 混色标志以使用绑定的 libgd 分层效果
    • imageline — 画一条线段
    • imageloadfont — 载入一新字体
    • imagepalettecopy — 将调色板从一幅图像拷贝到另一幅
    • imagepalettetotruecolor — Converts a palette based image to true color
    • imagepng — 以 PNG 格式将图像输出到浏览器或文件
    • imagepolygon — 画一个多边形
    • imagepsbbox — 给出一个使用 PostScript Type1 字体的文本方框
    • imagepsencodefont — 改变字体中的字符编码矢量
    • imagepsextendfont — 扩充或精简字体
    • imagepsfreefont — 释放一个 PostScript Type 1 字体所占用的内存
    • imagepsloadfont — 从文件中加载一个 PostScript Type 1 字体
    • imagepsslantfont — 倾斜某字体
    • imagepstext — 用 PostScript Type1 字体把文本字符串画在图像上
    • imagerectangle — 画一个矩形
    • imagerotate — 用给定角度旋转图像
    • imagesavealpha — 设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)
    • imagescale — Scale an image using the given new width and height
    • imagesetbrush — 设定画线用的画笔图像
    • imagesetinterpolation — Set the interpolation method
    • imagesetpixel — 画一个单一像素
    • imagesetstyle — 设定画线的风格
    • imagesetthickness — 设定画线的宽度
    • imagesettile — 设定用于填充的贴图
    • imagestring — 水平地画一行字符串
    • imagestringup — 垂直地画一行字符串
    • imagesx — 取得图像宽度
    • imagesy — 取得图像高度
    • imagetruecolortopalette — 将真彩色图像转换为调色板图像
    • imagettfbbox — 取得使用 TrueType 字体的文本的范围
    • imagettftext — 用 TrueType 字体向图像写入文本
    • imagetypes — 返回当前 PHP 版本所支持的图像类型
    • imagewbmp — 以 WBMP 格式将图像输出到浏览器或文件
    • imagewebp — 将 WebP 格式的图像输出到浏览器或文件
    • imagexbm — 将 XBM 图像输出到浏览器或文件
    • iptcembed — 将二进制 IPTC 数据嵌入到一幅 JPEG 图像中
    • iptcparse — 将二进制 IPTC 块解析为单个标记
    • jpeg2wbmp — 将 JPEG 图像文件转换为 WBMP 图像文件
    • png2wbmp — 将 PNG 图像文件转换为 WBMP 图像文件

用户评论:

[#1] Anonymous [2014-04-14 20:35:50]

<form action="index.php" method="POST" enctype="multipart/form-data">
Titel:
    <input type="text" name="titel" />
    File:
    <input type="file" name="image"> <input type="submit" name="submit" value="Verzend">
</form>

<?PHP 
//connection
include('connection.php');
if(isset(
$_POST['submit']))
{
    if((
$_POST['titel'])!="")
    {
        

$image $_FILES['image']['tmp_name'];
$titel $_REQUEST['titel'];

if (!isset(
$image))
    echo 
"Please upload an image" ;
    else
    {
        
$image_size getimagesize($_FILES['image']['tmp_name']);
        
        if(
$image_size==FALSE)
            echo 
"This is not an image, Nice Try!";
            else
            {
        
        
$image addslashes (file_get_contents ($_FILES['image']['tmp_name']));    
        
$image_name addslashes ($_FILES ['image']['name']);
        
$thumb imagecreatetruecolor(100,100);
        
$afb $_FILES['image'];
        
$temp $afb['tmp_name'];
        
$info getimagesize($temp);
        
$br $info['0'];
        
$hg $info['1'];
        
$ext $info['2'];
        
$source imagecreatefromjpeg($temp);
        
imagecopyresampled($thumb$source0000100100$br$hg);
        
$thumbname "database/thumb/tn".$image_name;
        
$thumbnailname "tn".$image_name;
        
imagejpeg ($thumb$thumbname);
        
move_uploaded_file ($_FILES['image']['tmp_name'], "database/".$image_name);
        
move_uploaded_file ($_FILES['image']['tmp_name'], "database/thumb/".$thumbname); 
        
        
                if (!
$insert mysql_query("INSERT INTO images VALUES('','$titel','$image_name','$thumbnailname')"))
                
                echo 
"Upload is not working.";
                else
                {
                    
                
$dir 'database/';
                
$base_url 'http://www.yourdomainname.com/foto/database';
                
$newest_mtime 0;
                
$show_file 'BROKEN';
                if (
$handle opendir($dir)) {
                 while (
false !== ($file readdir($handle))) {
                    if ((
$file != '.') && ($file != '..')) {
                       
$mtime filemtime("$dir/$file");
                       if (
$mtime $newest_mtime) {
                          
$newest_mtime $mtime;
                          
$show_file "$base_url/$file";
                                   }
                            }
                          }
                    }
                print 
'<img src="' .$show_file'" alt="$titel">';
                
//thumbnail
                
$dirthumb 'database/thumb/';
                
$base_urlthumb 'http://www.yourdomainname.com/foto/database/thumb';
                
$newest_mtime 0;
                
$show_file 'BROKEN';
                if (
$handle opendir($dirthumb)) {
                 while (
false !== ($file readdir($handle))) {
                    if ((
$file != '.') && ($file != '..')) {
                       
$mtime filemtime("$dirthumb/$file");
                       if (
$mtime $newest_mtime) {
                          
$newest_mtime $mtime;
                          
$show_file "$base_urlthumb/$file";
                                   }
                            }
                          }
                    }
                print 
'<img src="' .$show_file'" alt="$titel">';
                }
            }
    }
        
    }else { echo 
"Oops! Looks like you forgot to upload the image<br>"; }
}
    
    

?>

[#2] zsolt dot trenyik at gmail dot com [2013-08-12 06:33:21]

According to  kurdtpage at gmail dot com, we faced a fairly strange behavior of GD. We saved an incluce file incorrectly, and everything worked (OCI8, other php functions) except GD. It took one and half day to find the reason, at the end commenting out the require part of the main file. 

The solution was: we took a HEX editor to see if there is a problem with that .inc file. There was some crazy invisible characters before the <?php tag, signing that the text editor saved the file in utf format. These characters cannot be deleted, we had to open a new file in eclipse (notepad++ also works right), copy the visible part of the file to it, replace them, ready. 

Maybe this detailed warning helps somebody.

[#3] herbert dot walde at googlemail dot com [2012-01-04 11:41:15]

In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng(). 

And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.

Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.

Here is the full solution:

<?php
if(headers_sent()){
    die(
'Headers have been send somewhere within my script');
}

ob_clean(); //Clears the buffer

header('Content-type: image/png');
imagepng($imgNULL0,  NULL);

ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>

[#4] donatj at gmail dot com [2011-07-12 13:43:03]

UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.

[#5] kurdtpage at gmail dot com [2011-04-27 22:53:15]

When using GD, please make sure of the following things:

1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php

[#6] mac_doggie at hotmail dot com [2010-05-28 07:50:32]

A way to read the color of a pixel:

<?php
   $img 
imagecreatefrompng("image1.png");
   
   
$w imagesx($img);
   
$h imagesy($img);
   
   for(
$y=0;$y<$h;$y++) {
      for(
$x=0;$x<$w;$x++) {
         
$rgb imagecolorat($img$x$y);
         
$r = ($rgb >> 16) & 0xFF;
         
$g = ($rgb >> 8) & 0xFF;
         
$b $rgb 0xFF;         
         echo 
"#".str_repeat("0",2-strlen(dechex($r))).dechex($r).
str_repeat("0",2-strlen(dechex($g))).dechex($g).
str_repeat("0",2-strlen(dechex($b))).dechex($b).",";
      }
      echo 
"<br />\r\n";
   }
?>


[EDIT BY thiago: merged two notes from same submitter.]

[#7] mail at ecross dot nl [2010-04-03 07:31:02]

hello there,
i made a function to create a gradient image.

description:
gradient(int image_width, int image_height, 
int start_red, int start_green, int start_blue, 
int end_red, int end_green, int end_blue, 
bool vertical)

function:
<?php
function gradient($image_width$image_height,$c1_r$c1_g$c1_b$c2_r$c2_g$c2_b$vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;

// create a image
$image  imagecreatetruecolor($image_width$image_height); 

// make the gradient
for($i=0$i<$image_height$i++) 

$color_r floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;

$color ImageColorAllocate($image$color_r$color_g$color_b);
imageline($image0$i$image_width$i$color);


# Prints out all the figures and picture and frees memory 
header('Content-type: image/png'); 

if(
$vertical){$image imagerotate($image900);}
ImagePNG($image); 
imagedestroy($image); 
}
?>

[#8] Thomas [2008-12-10 14:05:35]

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.

[#9] code at ashleyhunt dot co dot uk [2008-10-23 18:02:57]

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(30050);
$text_color imagecolorallocate($im2331491);
imagestring($im155,  'A Simple Text String'$text_color);

// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($imNULL85);
// 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

上一篇: 下一篇: