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

search for in the

gd_info> <iis_stop_service
[edit] Last updated: Mon, 01 Nov 2010

view this page in

LXII. イメージ関数(image)

導入

PHPができることは、HTML出力を生成することだけではありません。PHP は、多くの異なるイメージ形式でイメージファイルを作成したり、操作 したりすることもできます。このイメージ形式には、gif, png, jpg, wbmp, xpmが含まれます。さらに便利なことに、PHPはイメージストリー ムを直接ブラウザに出力することができます。 これを動作されるには、イメージ関数のGDライブラリを指定してPHPをコ ンパイル必要があります。使用したいイメージ形式によっては、GDとPHP は他のライブラリも必要とする可能性があります。

PHPのイメージ関数により JPEGGIFPNGSWFTIFFJPEG2000イメージの 大きさを知ることができます。

exif 拡張モジュール を使用すると、 JPEGTIFF 画像のヘッダに保存された情報を扱うことができます。 これにより、デジタルカメラが作成したメタデータを読み込むことができます。 exif 関数は GD ライブラリを必要としません。

注意: イメージの読み込み、書き込み、修正の機能を拡張するには、 要求の節を呼んでください。 デジタルカメラで撮影した画像のメタデータを読み込むには、 上で説明した exif 拡張モジュール が必要です。

要件

GDライブラリ( http://www.boutell.com/gd/で取得可能)があれば、画像の作成と操 作を行なうこともできます。

操作できるイメージの形式は、インストールされている GDとこれらのイメージフォーマットにアクセスする ためにGDが必要とするその他のライブラリに依存し ます。gd-1.6より前のバージョンのgdは、GIFイメージ画像をサポートし ていますが、PNGはサポートしていません。一方、gd-1.6以降でgd-2.0.28未満の バージョンはPNGをサポートし、GIFはサポートしていません。 GIFサポートは、gd-2.0.28で再度有効になりました。

注意: PHP 4.3以降、GD libの付属版が付属しています。この付属版にはαブ レンディングのようないくつかの機能が追加されています。 この版のコードは、より管理が行き届き、安定しているため、 外部ライブラリの代わりに使用されるべきです。

注意: PHP 6.0.0 では GD 1.x はサポートされなくなりました。 GD 2.0.33 以降が必要となります。

より多くのイメージ形式を処理するために GD を拡張したいと思うかもしれません。

表 1. サポートされるイメージ形式

イメージ形式ダウンロードするライブラリ注記
gif  gd-1.6より以前またはgd-2.0.28以降のバージョンのGDでのみサポートされます。 読み込みのみのGIFサポートは、PHP 4.3.0 とバンドルされたGDライブラリの組合せで利用可能です。 書き込みのサポートは、PHP 4.3.9および PHP 5.0.1以降で利用可能です。
jpeg-6bftp://ftp.uu.net/graphics/jpeg/ 
pnghttp://www.libpng.org/pub/png/libpng.html gd-1.6以降のバージョンのGDでのみサポートされます。
xpmftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html Xウインドウ環境をインストールしている場合、 このライブラリを既に利用可能と思われます。

別の種類のフォントを処理できるようにGDを拡張したいと思うかもしれ ません。以下にサポートされるフォントライブラリを示します。

表 2. サポートされるフォントライブラリ

フォントライブラリダウンロード注記
FreeType 1.xhttp://www.freetype.org/PHP 6.0.0 でサポートされなくなりました。
FreeType 2http://www.freetype.org/ 
T1libftp://sunsite.unc.edu/pub/Linux/libs/graphics/) Postscript Type 1 フォントをサポートします。

インストール手順

PHPでGDサポートを有効にするには、configure に--with-gd[=DIR]を指定します。ただし、DIRは GDのベースインストールディレクトリです。 PHPにバンドルされている推奨のGDライブラリを使用するには --with-gdを指定します。 GD ライブラリをコンパイルするには、libpnglibjpeg が必要です。

Windowsの場合、GD2 DLL php_gd2.dllphp.iniに エクステンションとして指定してください。 GD1 DLL php_gd.dllはPHP4.3.2で削除されました。 imagecreatetruecolor()のようにTrueカラーが優先される関数 についてはGD2が必須です。

PHP3においてGDサポートを無効にするには --without-gdを指定してください。

より多くの画像フォーマットを扱えるようにGDの能力を高めるには、 --with-XXXXのような形のオプションを指定します。

表 3. サポートされる画像フォーマット

画像フォーマットconfigure オプション
jpeg-6b To enable support for jpeg-6b add --with-jpeg-dir=DIR.
png PNGをサポートするには--with-png-dir=DIR を指定します。ただし、libpngはzlibライブラリを 必要とするため、--with-zlib-dir[=DIR] もconfigureオプションに追加する必要があります。
xpm XPMをサポートするには--with-xpm-dir=DIR を指定します。必要なライブラリをconfigureが見つけられなかった場合は X11ライブラリのパスを追加してください。

注意: libpng と共に PHP をコンパイルする際、GD ライブラリとリンクされる同じバージョンを使用する必要があります。

GDがより多くのフォントを扱えるようにするには --with-XXXXのような形のオプションを指定します。

表 4. サポートされるフォントライブラリ

フォントライブラリconfigure オプション
FreeType 1.x FreeType 1.x をサポートするには --with-ttf[=DIR]を指定します。
FreeType 2 FreeType 2 をサポートするには --with-freetype-dir=DIRを指定します。
T1lib T1lib (Postscript Type 1 フォント) をサポートするには --with-t1lib[=DIR]を指定します。
ネイティブ TrueType 文字列関数 ネイティブな TrueType 文字列関数 をサポートするには --enable-gd-native-ttfを指定します。

実行時設定

イメージ関数固有の設定項目はありませんが、 exif 拡張モジュール のディレクティブに興味を持つかも知れません。

リソース型

リソース型は定義されていません。

定義済み定数

以下の定数が定義されています。 この関数の拡張モジュールが PHP 組み込みでコンパイルされているか、 実行時に動的にロードされている場合のみ使用可能です。

IMG_GIF (integer)

IMG_JPG (integer)

IMG_JPEG (integer)

IMG_PNG (integer)

IMG_WBMP (integer)

IMG_XPM (integer)

IMG_COLOR_TILED (integer)

IMG_COLOR_STYLED (integer)

IMG_COLOR_BRUSHED (integer)

IMG_COLOR_STYLEDBRUSHED (integer)

IMG_COLOR_TRANSPARENT (integer)

IMG_ARC_ROUNDED (integer)

IMG_ARC_PIE (integer)

IMG_ARC_CHORD (integer)

IMG_ARC_NOFILL (integer)

IMG_ARC_EDGED (integer)

IMAGETYPE_GIF (integer)

IMAGETYPE_JPEG (integer)

IMAGETYPE_PNG (integer)

IMAGETYPE_SWF (integer)

IMAGETYPE_PSD (integer)

IMAGETYPE_BMP (integer)

IMAGETYPE_WBMP (integer)

IMAGETYPE_XBM (integer)

IMAGETYPE_TIFF_II (integer)

IMAGETYPE_TIFF_MM (integer)

IMAGETYPE_IFF (integer)

IMAGETYPE_JB2 (integer)

IMAGETYPE_JPC (integer)

IMAGETYPE_JP2 (integer)

IMAGETYPE_JPX (integer)

IMAGETYPE_SWC (integer)

例 1. PHPによるPNGの生成

<?php

header
("Content-type: image/png");
$string = $_GET['text'];
$im     = imagecreatefrompng("images/button1.png");
$orange = imagecolorallocate($im, 220, 210, 60);
$px     = (imagesx($im) - 7.5 * strlen($string)) / 2;
imagestring($im, 3, $px, 9, $string, $orange);
imagepng($im);
imagedestroy($im);

?>
この例のスクリプトは、<img src="button.php?text"> のようなタグによりあるページからコールされるものです。 上のbutton.phpスクリプトは、この "text" 文字列を引数と し、この場合は "images/button1.png" である基本イメージ の最上部にこの文字列を描いた後、描画後ののイメージを出力します。 この方法は、ボタンのテキストを変更する度に新規のボタンを生成する 必要があるのを回避するために便利な手法です。 この方法により、動的にイメージボタンを生成できます。

目次
gd_info -- 現在インストールされているGDライブラリに関する情報を取得する
getimagesize -- 画像の大きさを取得する
image_type_to_extension --  画像形式からファイルの拡張子を取得する
image_type_to_mime_type --  getimagesize, exif_read_data, exif_thumbnail, exif_imagetypeから返される 画像形式のMIMEタイプを取得する
image2wbmp -- ブラウザまたはファイルにイメージを出力する
imagealphablending -- イメージをblendingモードに設定する
imageantialias --  アンチエイリアス機能を使用すべきかどうかを判断する
imagearc -- 部分楕円の描画
imagechar -- 水平に文字を描画
imagecharup -- 垂直に文字を描画
imagecolorallocate -- 画像で使用する色を作成する
imagecolorallocatealpha -- 画像で使用する色を透過度を指定して作成する
imagecolorat -- ピクセルの色のインデックスを取得
imagecolorclosest --  指定した色に最も近い色のインデックスを取得する
imagecolorclosestalpha --  指定した色+アルファ値に最も近い色のIDを取得
imagecolorclosesthwb --  指定した色に最も近い色合い、白、黒を有する色のインデックスを得る
imagecolordeallocate --  イメージの色リソースを開放する
imagecolorexact -- 指定した色のインデックスを取得する
imagecolorexactalpha -- 指定した色+アルファ値のIDを取得
imagecolormatch --  パレットイメージの色をTrueカラーイメージに近づける
imagecolorresolve --  指定した色または出来るだけ近い色のインデックスを得る
imagecolorresolvealpha --  指定した色+アルファ値または最も近い色のIDを取得する
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 から新規 JPEG 画像を作成する
imagecreatefrompng -- ファイルまたは URL から新規 PNG 画像を作成する
imagecreatefromstring --  文字列の中のイメージストリームから新規イメージを作成する
imagecreatefromwbmp --  ファイルまたは URL から新規イメージを作成する
imagecreatefromxbm -- ファイル又はURLから新規イメージを生成する
imagecreatefromxpm -- ファイルまたはURLから新規イメージを生成する
imagecreatetruecolor -- TrueColor イメージを新規に作成する
imagedashedline -- ダッシュライン(破線)の描画
imagedestroy -- 画像の消去
imageellipse -- 楕円を描画する
imagefill -- 塗り潰し
imagefilledarc -- 部分楕円を描画し、塗りつぶす
imagefilledellipse -- 塗りつぶされた楕円を描画する
imagefilledpolygon -- 塗りつぶした多角形の描画
imagefilledrectangle -- 塗りつぶした矩形の描画
imagefilltoborder -- 特定色での塗りつぶし
imagefilter --  画像にフィルタを適用する
imagefontheight -- フォントの高さの取得
imagefontwidth -- フォントの幅の取得
imageftbbox --  freetype2によるフォントを用いたテキストを囲む箱を取得する
imagefttext --  FreeType 2によるフォントを用いてイメージにテキストを描画する
imagegammacorrect --  GDイメージにガンマ補正を適用する
imagegd2 --  GD2 イメージをブラウザまたはファイルに出力する
imagegd --  GD イメージをブラウザまたはファイルに出力する
imagegif -- ブラウザまたはファイルへ画像を出力する
imageinterlace -- インターレースを有効もしくは無効にする
imageistruecolor -- 画像がtrueカラーかどうか調べる
imagejpeg -- 画像をブラウザまたはファイルに出力する
imagelayereffect --  アルファブレンディングフラグを設定し、libgd にバンドルされている レイヤ効果を使用する
imageline -- 直線の描画
imageloadfont -- 新規フォントのロード
imagepalettecopy --  あるイメージから他のイメージにパレットをコピーする
imagepng --  PNG イメージをブラウザまたはファイルに出力する
imagepolygon -- 多角形の描画
imagepsbbox --  PostScript Type1 フォントを用いてテキスト矩形のバウンディングボックス を指定する
imagepsencodefont -- フォントの文字エンコードベクトルを変更する
imagepsextendfont -- フォントを展開または圧縮する
imagepsfreefont -- PostScript Type 1 フォント用メモリを解放する
imagepsloadfont -- ファイルから PostScript Type 1 フォントをロードする
imagepsslantfont -- フォントを傾ける
imagepstext --  PostScript Type1 フォントを用いて画像の上に文字列を描く
imagerectangle -- 矩形の描画
imagerotate -- 指定された角度で画像を回転する
imagesavealpha --  PNG 画像を保存する際に(単一色の透過設定ではない)完全な アルファチャネル情報を保存するフラグを設定する
ImageSetBrush -- 線の描画用にブラシイメージを設定する
imagesetpixel -- 点の生成
imagesetstyle -- 線描画用のスタイルを設定する
imagesetthickness -- 線描画用の線幅を設定する
imagesettile -- 塗りつぶし用のイメージを設定する
imagestring -- 文字列を水平に描画する
imagestringup -- 文字列を垂直に描画する
imagesx -- 画像の幅を取得
imagesy -- 画像の高さを取得する
imagetruecolortopalette -- TrueColorイメージをパレットイメージに変換する
imagettfbbox --  TypeType フォントを使用したテキストの bounding box の生成
imagettftext -- TrueType フォントを使用してテキストを画像に書き込む
imagetypes --  使用中のPHPの実行ファイルでサポートされているイメージの型を返す
imagewbmp -- ブラウザまたはファイルにイメージを出力する
imagexbm --  XBM 画像をブラウザあるいはファイルに出力する
iptcembed --  バイナリIPTCデータをJPEGイメージに埋めこむ
iptcparse --  バイナリの IPTC http://www.iptc.org/ ブロックを パースする
jpeg2wbmp --  JPEGイメージファイルからWBMPイメージファイルに変換する
png2wbmp --  PNGイメージファイルからWBMPイメージファイルに変換する


gd_info> <iis_stop_service
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes イメージ関数(image)
ingo at jache dot de 14-Oct-2011 03:16
I know this might look somewhat superfluous to others, but i once came across a situation where i needed a *strong* blur on an image without having ImageMagick installed. Executing the convolution-filter several times on the same image is awfully slow and still doesn't give a good blur.

The function below accepts a truecolor-image and a blur-factor between 0.0 and 1.0. Beware: It's still quite slow.

<?php

   
function blurImage($srcimg,$blur)
    {
       
$blur = $blur*$blur;
       
$blur = max(0,min(1,$blur));
   
       
$srcw = imagesx($srcimg);
       
$srch = imagesy($srcimg);
       
       
$dstimg = imagecreatetruecolor($srcw,$srch);
   
       
$f1a = $blur;
       
$f1b = 1.0 - $blur;

   
       
$cr = 0; $cg = 0; $cb = 0;
       
$nr = 0; $ng = 0; $nb = 0;

       
$rgb = imagecolorat($srcimg,0,0);
       
$or = ($rgb >> 16) & 0xFF;
       
$og = ($rgb >> 8) & 0xFF;
       
$ob = ($rgb) & 0xFF;

       
//-------------------------------------------------
        // first line is a special case
        //-------------------------------------------------
       
$x = $srcw;
       
$y = $srch-1;
        while (
$x--)
        {
           
//horizontal blurren
           
$rgb = imagecolorat($srcimg,$x,$y);
           
$cr = ($rgb >> 16) & 0xFF;
           
$cg = ($rgb >> 8) & 0xFF;
           
$cb = ($rgb) & 0xFF;
   
           
$nr = ($cr * $f1a) + ($or * $f1b);
           
$ng = ($cg * $f1a) + ($og * $f1b);
           
$nb = ($cb * $f1a) + ($ob * $f1b);   

           
$or = $nr;
           
$og = $ng;
           
$ob = $nb;
           
           
imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
        }
       
//-------------------------------------------------

        //-------------------------------------------------
        // now process the entire picture
        //-------------------------------------------------
       
$y = $srch-1;
        while (
$y--)
        {

           
$rgb = imagecolorat($srcimg,0,$y);
           
$or = ($rgb >> 16) & 0xFF;
           
$og = ($rgb >> 8) & 0xFF;
           
$ob = ($rgb) & 0xFF;

           
$x = $srcw;
            while (
$x--)
            {
               
//horizontal
               
$rgb = imagecolorat($srcimg,$x,$y);
               
$cr = ($rgb >> 16) & 0xFF;
               
$cg = ($rgb >> 8) & 0xFF;
               
$cb = ($rgb) & 0xFF;
               
               
$nr = ($cr * $f1a) + ($or * $f1b);
               
$ng = ($cg * $f1a) + ($og * $f1b);
               
$nb = ($cb * $f1a) + ($ob * $f1b);   
   
               
$or = $nr;
               
$og = $ng;
               
$ob = $nb;
               
               
               
//vertical
               
$rgb = imagecolorat($dstimg,$x,$y+1);
               
$vr = ($rgb >> 16) & 0xFF;
               
$vg = ($rgb >> 8) & 0xFF;
               
$vb = ($rgb) & 0xFF;
               
               
$nr = ($nr * $f1a) + ($vr * $f1b);
               
$ng = ($ng * $f1a) + ($vg * $f1b);
               
$nb = ($nb * $f1a) + ($vb * $f1b);   
   
               
$vr = $nr;
               
$vg = $ng;
               
$vb = $nb;
               
               
imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
            }
       
        }
       
//-------------------------------------------------
       
return $dstimg;       

    }

   
   
$srcimg = imagecreatefromjpeg("test.jpg");
   
$dstimg = blurImage($srcimg,0.2);

   
header('Content-type: image/jpeg');
    echo(
imagejpeg($dstimg) );
    exit();
   
   
?>
chuckstudios at gmail dot com 25-Nov-2008 09:18
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you:

<?php
   
function imagepgm($image, $filename = null)
    {
       
$pgm = "P5 ".imagesx($image)." ".imagesy($image)." 255\n";
        for(
$y = 0; $y < imagesy($image); $y++)
        {
            for(
$x = 0; $x < imagesx($image); $x++)
            {
               
$colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
               
$pgm .= chr(0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]);
            }
        }
        if(
$filename != null)
        {
           
$fp = fopen($filename, "w");
           
fwrite($fp, $pgm);
           
fclose($fp);
        }
        else
        {
            return
$pgm;
        }
    }
?>
dev at kingthief dot com 28-Mar-2008 08:20
I've developed a well-documented, fairly rock-solid API for creating on the fly, anti-aliased, rounded corner images, including full alpha transparency support for all you PNG lovers.

go here to download the package:
http://sourceforge.net/projects/roundedphp/

go here for a live demo:
http://dev.kingthief.com/demos/roundedphp/

Installation is similar to PEAR.

Enjoy!
ph_corp at yahoo dot fr 23-Dec-2007 03:19
<?php

/**
HSL/RGB conversion functions
very useful for a lot of applications
**/

function RBGtoHSL ( $R, $G, $B )
{

   
$var_R = ( $R / 255 );
   
$var_G = ( $G / 255 );
   
$var_B = ( $B / 255 );

   
$var_Min = min( $var_R, $var_G, $var_B )
   
$var_Max = max( $var_R, $var_G, $var_B )
   
$del_Max = $var_Max - $var_Min

    $L
= ( $var_Max + $var_Min ) / 2;

    if (
$del_Max == 0 )
    {
      
$H = 0
       $S
= 0
   
}
    else
    {
        if (
$L < 0.5 )
        {
           
$S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
           
$S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

       
$del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
       
$del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
       
$del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if (
$var_R == $var_Max )
        {
           
$H = $del_B - $del_G;
        }
        else if (
$var_G == $var_Max )
        {
           
$H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if (
$var_B == $var_Max )
        {
           
$H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if (
$H < 0 )
        {
           
$H += 1;
        }
        if (
$H > 1 )
        {
           
$H -= 1
       
}

    }

    return array(
$H, $S, $L );

}

function
HuetoRGB( $v1, $v2, $vH )
{
    if (
$vH < 0 )
    {
       
$vH += 1;
    }
    if (
$vH > 1 )
    {
       
$vH -= 1;
    }
    if ( (
6 * $vH ) < 1 )
    {
        return (
$v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( (
2 * $vH ) < 1 )
    {
        return (
$v2 );
    }
    if ( (
3 * $vH ) < 2 )
    {
        return (
$v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return (
$v1 )
}

function
HSLtoRGB ( $H, $S, $L )
{

    if (
$S == 0 )
    {
       
$R = $L * 255;
       
$G = $L * 255;
       
$B = $L * 255;
    }
    else
    {
        if (
$L < 0.5 )
        {
           
$var_2 = $L * ( 1 + $S );
        }
        else
        {
           
$var_2 = ( $L + $S ) - ( $S * $L );
        }

       
$var_1 = 2 * $L - $var_2;

       
$R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
       
$G = 255 * HuetoRGB( $var_1, $var_2, $H );
       
$B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array(
$R, $G, $B );

}

function
distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
   
$result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return (
$result );
}

?>
shd at earthling dot net 28-Mar-2006 04:44
If you happen to need a way to output a Windows BMP file (e.g. when using the PEAR ExcelWriter), feel free to use the following code:

<?php
function imagebmp ($im, $fn = false)
{
    if (!
$im) return false;
           
    if (
$fn === false) $fn = 'php://output';
   
$f = fopen ($fn, "w");
    if (!
$f) return false;
           
   
//Image dimensions
   
$biWidth = imagesx ($im);
   
$biHeight = imagesy ($im);
   
$biBPLine = $biWidth * 3;
   
$biStride = ($biBPLine + 3) & ~3;
   
$biSizeImage = $biStride * $biHeight;
   
$bfOffBits = 54;
   
$bfSize = $bfOffBits + $biSizeImage;
           
   
//BITMAPFILEHEADER
   
fwrite ($f, 'BM', 2);
   
fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
           
   
//BITMAPINFO (BITMAPINFOHEADER)
   
fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));
           
   
$numpad = $biStride - $biBPLine;
    for (
$y = $biHeight - 1; $y >= 0; --$y)
    {
        for (
$x = 0; $x < $biWidth; ++$x)
        {
           
$col = imagecolorat ($im, $x, $y);
           
fwrite ($f, pack ('V', $col), 3);
        }
        for (
$i = 0; $i < $numpad; ++$i)
           
fwrite ($f, pack ('C', 0));
    }
   
fclose ($f);
    return
true;
}
?>

It works the same way as regular imagejpeg/imagepng do and only supports GD2.0 true colour bitmaps (which is what's required by ExcelWriter).
felipensp at gmail dot com 12-Mar-2006 09:17
Representation decimal of a color in hexadecimal for use on functions of library GD.

<?php

   
// Representation hexadecimal
   
$var = '#FFFFFF';

    function
getRgbFromGd($color_hex) {

        return
array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));

    }
   
   
print_r(getRgbFromGd($var));

   
// Output: Array ( [0] => 255 [1] => 255 [2] => 255 )

?>
peter dot hulstaert at gmail dot com 05-Jan-2006 05:18
While I was searching for a good way to draw a graph, I stumbled on skumar2k15's script.

I have taken the liberty to improve multiple aspects of it.

1. The array can grow and shrink in size, the graph will adjust accordingly.
2. All the values in the array are recalculated so they won't get bigger than the height of the graph.
3. I inserted the possibility to keep a percentage off the height away from the edge.
4. You can adjust the size of the grid.
5. Everything will adjust when you change the height of width.

<?
header
("Content-type: image/png");

// Define variables
$Values=array(50,90,30,155,50,40,320,50,40,86,240,128,650,540,320);
$imgWidth=500;
$imgHeight=200;
$grid=25;
$graphspacing=0.05;

//Creation of new array with hight adjusted values
while (list($key, $val) = each($Values))
    {if(
$val>$max){$max=$val;}}

for (
$i=0; $i<count($Values); $i++){
$graphValues[$i] = $Values[$i] * (($imgHeight*(1-$graphspacing))/$max);
}
// Create image and define colors

$image=imagecreate($imgWidth, $imgHeight);
$colorWhite=imagecolorallocate($image, 255, 255, 255);
$colorGrey=imagecolorallocate($image, 192, 192, 192);
$colorBlue=imagecolorallocate($image, 0, 0, 255);

// Create border around image
imageline($image, 0, 0, 0, $imgHeight, $colorGrey);
imageline($image, 0, 0, $imgWidth, 0, $colorGrey);
imageline($image, $imgWidth-1, 0, $imgWidth-1, $imgHeight-1, $colorGrey);
imageline($image, 0, $imgHeight-1, $imgWidth-1, $imgHeight-1, $colorGrey);

// Create grid
for ($i=1; $i<($imgWidth/$grid); $i++)
    {
imageline($image, $i*$grid, 0, $i*$grid, $imgHeight, $colorGrey);}
for (
$i=1; $i<($imgHeight/$grid); $i++)
    {
imageline($image, 0, $i*$grid, $imgWidth, $i*$grid, $colorGrey);}

// Create line graph
if($imgWidth/$grid>count($graphValues)){$space=$grid;}
else{
$space = $imgWidth/(count($graphValues)-1);}

for (
$i=0; $i<count($graphValues)-1; $i++)
    {
imageline($image, $i*$space, ($imgHeight-$graphValues[$i]), ($i+1)*$space, ($imgHeight-$graphValues[$i+1]), $colorBlue);}

// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
michal-ok at o2 dot pl 18-Oct-2005 02:29
The image sharpen function (by Alex R. Austin) provided below seems to be very resource hungry and I couldn't make it work on two different servers - trying to sharpen a 413 x 413 image I ended up with "Fatal error: Allowed memory size of 8388608 bytes exhausted" or "Internal Server Error" or the script terminated without notice. Because I had no priviliges to change the default memory limit on these servers I started looking for other sharpen functions. I have come across a php Unsharp Mask function which works like a charm on both of the servers I dealt with. It can be found at http://vikjavev.no/hovudsida/umtestside.php.
mslemko 09-Oct-2005 12:09
For fedora core 4 users that find that the gd library isn't installed, you can issue the command (as root)

# yum install php-gd

it should download and install the gd library. You will need to restart apache... phpinfo() should then tell you "GD Support     enabled".
timeshifting at gmail dot com 24-Aug-2005 03:39
To sharpen an image, rather than using the code below that produces a sharpening filter with php, use the built-in GD function "imageconvolution" which is designed for this purpose. Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix
= array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html
jeff at lushmedia dot com 04-Nov-2003 08:52
I wrote an online overview of the image functions that people might find useful. In addition to a general overview of the various function categories and code samples, I have included many interactive examples of the functions, allowing viewers to experiment with the parameters, and seeing the results in real time. The presentation is located at New York PHP
http://www.nyphp.org/content/presentations/GDintro/
sellout at NoSpAm dot dharmadevil dot com 16-Apr-2003 10:06
A fun little function to output UPC-A 11-digit barcodes.
Thanks to barcodeisland.com for the specs.

<?php

function UPCAbarcode($code) {
 
$lw = 2; $hi = 100;
 
$Lencode = array('0001101','0011001','0010011','0111101','0100011',
                  
'0110001','0101111','0111011','0110111','0001011');
 
$Rencode = array('1110010','1100110','1101100','1000010','1011100',
                  
'1001110','1010000','1000100','1001000','1110100');
 
$ends = '101'; $center = '01010';
 
/* UPC-A Must be 11 digits, we compute the checksum. */
 
if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
 
/* Compute the EAN-13 Checksum digit */
 
$ncode = '0'.$code;
 
$even = 0; $odd = 0;
  for (
$x=0;$x<12;$x++) {
    if (
$x % 2) { $odd += $ncode[$x]; } else { $even += $ncode[$x]; }
  }
 
$code.=(10 - (($odd * 3 + $even) % 10)) % 10;
 
/* Create the bar encoding using a binary string */
 
$bars=$ends;
 
$bars.=$Lencode[$code[0]];
  for(
$x=1;$x<6;$x++) {
   
$bars.=$Lencode[$code[$x]];
  }
 
$bars.=$center;
  for(
$x=6;$x<12;$x++) {
   
$bars.=$Rencode[$code[$x]];
  }
 
$bars.=$ends;
 
/* Generate the Barcode Image */
 
$img = ImageCreate($lw*95+30,$hi+30);
 
$fg = ImageColorAllocate($img, 0, 0, 0);
 
$bg = ImageColorAllocate($img, 255, 255, 255);
 
ImageFilledRectangle($img, 0, 0, $lw*95+30, $hi+30, $bg);
 
$shift=10;
  for (
$x=0;$x<strlen($bars);$x++) {
    if ((
$x<10) || ($x>=45 && $x<50) || ($x >=85)) { $sh=10; } else { $sh=0; }
    if (
$bars[$x] == '1') { $color = $fg; } else { $color = $bg; }
   
ImageFilledRectangle($img, ($x*$lw)+15,5,($x+1)*$lw+14,$hi+5+$sh,$color);
  }
 
/* Add the Human Readable Label */
 
ImageString($img,4,5,$hi-5,$code[0],$fg);
  for (
$x=0;$x<5;$x++) {
   
ImageString($img,5,$lw*(13+$x*6)+15,$hi+5,$code[$x+1],$fg);
   
ImageString($img,5,$lw*(53+$x*6)+15,$hi+5,$code[$x+6],$fg);
  }
 
ImageString($img,4,$lw*95+17,$hi-5,$code[11],$fg);
 
/* Output the Header and Content. */
 
header("Content-Type: image/png");
 
ImagePNG($img);
}

UPCAbarcode('12345678901');

?>

 
show source | credits | sitemap | contact | advertising | mirror sites