|
|
XLV. イメージ関数(image)
PHPができることは、HTML出力を生成することだけではありません。PHP
は、多くの異なるイメージ形式でイメージファイルを作成したり、操作
したりすることもできます。このイメージ形式には、gif, png, jpg,
wbmp, xpmが含まれます。さらに便利なことに、PHPはイメージストリー
ムを直接ブラウザに出力することができます。
これを動作されるには、イメージ関数のGDライブラリを指定してPHPをコ
ンパイル必要があります。使用したいイメージ形式によっては、GDとPHP
は他のライブラリも必要とする可能性があります。
PHPのイメージ関数により
JPEG、GIF、
PNG、SWF、
TIFF、JPEG2000イメージの
大きさを知ることができます。
注意:
イメージの読み込み、書き込み、修正の機能の拡張、デジタルカメラ
により撮影された画像のメタデータを読み込むには、要求の節を読ん
で下さい。
GDライブラリ( で取得可能)があれば、画像の作成と操
作を行なうこともできます。
操作できるイメージの形式は、インストールされている
GDとこれらのイメージフォーマットにアクセスする
ためにGDが必要とするその他のライブラリに依存し
ます。gd-1.6より前のバージョンのgdは、GIFイメージ画像をサポートし
ていますが、PNGはサポートしていません。一方、gd-1.6以降のバージョ
ンはPNGをサポートし、GIFはサポートしていません。
注意:
PHP 4.3以降、GD libの付属版が付属しています。この付属版にはαブ
レンディングのようないくつかの機能が追加されています。
この版のコードは、より管理が行き届き、安定しているため、
外部ライブラリの代わりに使用されるべきです。
より多くのイメージ形式を処理するためにGDを拡張したいと思うかもし
れません。
表 1. サポートされるイメージ形式 イメージ形式 | ダウンロードするライブラリ | 注記 |
---|
gif | |
gd-1.6より以前のバージョンのGDでのみサポートされます。
読み込みのみのGIFサポートは、PHP 4.3.0
とバンドルされたGDライブラリの組合せで利用可能です。
| jpeg-6b | | | png | |
gd-1.6以降のバージョンのGDでのみサポートされます。
| xpm | |
Xウインドウ環境をインストールしている場合、
このライブラリを既に利用可能と思われます。
|
別の種類のフォントを処理できるようにGDを拡張したいと思うかもしれ
ません。以下にサポートされるフォントライブラリを示します。
表 2. サポートされるフォントライブラリ フォントライブラリ | ダウンロード | 注記 |
---|
FreeType 1.x | | | FreeType 2 | | | T1lib | ) |
Type 1フォントをサポートします。
|
--enable-exifを指定してPHPをコ
ンパイルした場合、JPEGおよび
TIFFイメージのヘッダに格納された情報を処理する
ことができるようになります。これにより、以下に示すようにデジタル
カメラにより生成されたメタデータを読むことができるようになります。
以下の関数は、GDライブラリを必要としません。
注意:
PHPは、exifモジュール用のライブラリの追加を必要としません。
PHPでGDサポートを有効にするには、configure に--with-gd[=DIR]を指定します。ただし、DIRは
GDのベースインストールディレクトリです。
PHPにバンドルされている推奨のGDライブラリを使用するには
--with-gdを指定します。
Windowsの場合、GD2 DLL php_gd2.dllをphp.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ライブラリのパスを追加してください。
|
GDがより多くのフォントを扱えるようにするには
--with-XXXXのような形のオプションを指定します。
line.
表 4. サポートされるフォントライブラリ フォントライブラリ | configure オプション |
---|
FreeType 1.x |
FreeType 1.x をサポートするには
--with-ttf[=DIR]を指定します。
| FreeType 2 |
FreeType 2 をサポートするには
--with-freetype-dir=DIRを指定します。
| T1lib |
T1lib (Type 1 fonts) をサポートするには
--with-t1lib[=DIR]を指定します。
| ネイティブ TrueType 文字列関数 |
ネイティブな TrueType 文字列関数 をサポートするには
--enable-gd-native-ttfを指定します。
|
これらの関数の動作は、php.iniの設定により変化します。
Exifは、モジュールmbstringが利用
可能な場合に、UnicodeとユーザコメントのJIS文字エンコーディングの変換を
自動的にサポートします。これは、指定された文字セットを用いてまずコメ
ントをデコードすることにより行なわれます。次にこの結果は
HTTP出力にマッチする他の文字セットにエンコードされます。
表 5. Exif 設定オプション 名前 | デフォルト値 | 変更可能範囲 |
---|
exif.encode_unicode | "ISO-8859-15" | PHP_INI_ALL | exif.decode_unicode_motorola | "UCS-2BE" | PHP_INI_ALL | exif.decode_unicode_intel | "UCS-2LE" | PHP_INI_ALL | exif.encode_jis | "" | PHP_INI_ALL | exif.decode_jis_motorola | "JIS" | PHP_INI_ALL | exif.decode_jis_intel | "JIS" | PHP_INI_ALL |
PHP_INI_*定数に関する詳細と定義については、
ini_set()を参照して下さい。
以下に設定ディレクティブに関す
る簡単な説明を示します。
- exif.encode_unicode
string
exif.encode_unicode は、UNICODEユーザコメント
が処理される文字セットを定義します。ISO-8859-15がデフォルトとなっ
ており、アジア圏を除く多くの地域では動作するはずです。
この設定値は空またはmbstringでサポートされるエンコーディング
とすることができます。空の場合、mbstringのカレントの
内部エンコーディングが使用されます。
- exif.decode_unicode_motorola
string
exif.decode_unicode_motorola は、イメージが
モトローラバイトオーダ(ビッグインディアン)の場合に、
Unicodeエンコードされたユーザコメントのイメージの内部文字
セットを定義します。
この設定値は空とすることができませんが、mbstringでサポートされる
エンコーディングのリストを指定するとすることができます。
デフォルトは、デフォルトは、UCS-2BEです。
- exif.decode_unicode_intel
string
exif.decode_unicode_intel は、イメージがイン
テルバイトオーダ(リトルインディアン)の場合に、Unicodeエンコード
されたユーザコメントのイメージの内部文字セットを定義します。
この設定値は空とすることができませんが、mbstringでサポートされる
エンコーディングのリストを指定するとすることができます。デフォル
トは、デフォルトは、UCS-2LEです。
- exif.encode_jis
string
exif.encode_jis は、JIS文字セットの
ユーザコメントの処理を定義します。デフォルト値は空であり、
mbstringのカレントの内部エンコーディングを関数が使用する
ようになっています。
- exif.decode_jis_motorola
string
exif.decode_jis_motorola は、イメージが
モトローラバイトオーダ(ビッグインディアン)の場合に、
JISエンコードされたユーザコメントのイメージの内部文字
セットを定義します。
この設定値は空とすることができませんが、mbstringでサポートされる
エンコーディングのリストを指定するとすることができます。
デフォルトは、デフォルトは、JISです。
- exif.decode_jis_intel
string
exif.decode_jis_intel は、イメージが
インテルバイトオーダ(リトルインディアン)の場合に、
JISエンコードされたユーザコメントのイメージの内部文字
セットを定義します。
この設定値は空とすることができませんが、mbstringでサポートされる
エンコーディングのリストを指定するとすることができます。
デフォルトは、デフォルトは、JISです。
この拡張モジュールはリソース型を全く定義しません。
これらの定数は、この拡張モジュールで定義されており、
この拡張モジュールがPHP内部にコンパイルされているか実行時に動的にロー
ドされるかのどちらかの場合のみ使用可能です。
例 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" である基本イメージ
の最上部にこの文字列を描いた後、描画後ののイメージを出力します。
この方法は、ボタンのテキストを変更する度に新規のボタンを生成する
必要があるのを回避するために便利な手法です。
この方法により、動的にイメージボタンを生成できます。
KaHa6uc at abv dot bg
14-Mar-2005 05:53
When generating an image (my case was a counter, and I needed to load it every time), some browsers, Opera was this particular case, received the "HTTP/1.1 301 Not Modified" header, so it skipped loading it and took it from the cache. The best workaround for this was to use
header("HTTP/1.1 202 Accepted");
before sending the image as a direct output:
header("HTTP/1.1 202 Accepted");
header("Content-type: image/gif");
Thus the image is now loaded every time ;)
---------------------------------------------------
Division from within invalidates suffering
andreaskalsch at gmx dot de
09-Mar-2005 06:24
You get some trouble if you create an image by using the function imagettfbbox(). The x value is correct but the y value doesn't consider that a text can have more than one line.
The second problem is to find the start position when you want to use imagettftext(), especially by using an angle > 90�.
My solution uses some params to generate an image with any text. The image size is as small as possible, but you can add a margin without problems:
params:
$text > the string you want to write
$format > output format "jpeg" or "png"
$quality > jpeg quality, from 1 to 100
$font > font path and file
$size > font size (px)
$angle > angle of text in degrees
$r > font color: red part
$g > font color: green part
$b > font color: blue part
$bgr > background color: red part
$bgg > bg color: green part
$bgb > bg color: blue part
$margin > a margin between text and border of pic
code:
<?
if ($text != '')
{
list(,,$w) = imagettfbbox($size, 0, $font, $text);
$lines = count(explode("\n", $text));
$angle_rad = $angle / 180 * pi();
$h = 2 * $size * $lines;
$x = round($h * abs(sin($angle_rad)) + $w * abs(cos($angle_rad))) + $size;
$y = round($h * abs(cos($angle_rad)) + $w * abs(sin($angle_rad))) + $size;
$run_y = - $lines * $size + 1.5 * $size;
$s_x = round($x / 2 - ($w / 2) * cos($angle_rad) + $run_y * sin($angle_rad));
$s_y = round($y / 2 + ($w / 2) * sin($angle_rad) + $run_y * cos($angle_rad));
$im = imagecreatetruecolor($x, $y);
@imageantialias($im, true);
$bg = imagecolorallocate ($im, $bgr, $bgg, $bgb);
$tx = imagecolorallocate ($im, $r, $g, $b);
imagefill($im, 0, 0, $bg);
imagettftext ($im, $size, $angle, $s_x, $s_y, $tx, $font, $text);
for ($x = 0; $x < imagesx($im); $x++)
{
for ($y = 0; $y < imagesy($im); $y++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$left = $x;
for ($x = imagesx($im) - 1; $x >= 0; $x--)
{
for ($y = 0; $y < imagesy($im); $y++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$right = $x;
for ($y = 0; $y < imagesy($im); $y++)
{
for ($x = 0; $x < imagesx($im); $x++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$top = $y;
for ($y = imagesy($im) - 1; $y >= 0; $y--)
{
for ($x = 0; $x < imagesx($im); $x++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$bottom = $y;
$cut = imagecreatetruecolor($right - $left + 1 + $margin * 2, $bottom - $top + 1 + $margin * 2);
$bg_ = imagecolorallocate ($cut, $bgr, $bgg, $bgb);
imagefill($cut, 0, 0, $bg_);
imagecopy ($cut, $im, $margin, $margin, $left, $top, $right - $left + 1, $bottom - $top + 1);
if ($format == 'jpeg')
{
header("Content-type:image/jpeg");
imagejpeg($cut,false,$quality);
}
elseif ($format == 'png')
{
header("Content-type:image/png");
imagepng($cut);
}
}
?>
you can download an interface soon:
rob schifreen
09-Mar-2005 11:23
A google search for "imagecolorgradient horizontal" will show you a modified version of the code by "solanki" (above) which allows a choice between horizontal and vertical gradient fill.
This works very well.
Also note that you need to change any occurrence of "imagecreate" to "imagecreatetruecolor" if you will be filling an image that has more than 255 rows or columns. Otherwise the function will not be able to create more than 255 colours and the results will not look right.
domNOSPAMinic at epicwebservices dot net
24-Feb-2005 12:04
Here's a simple function to deinterlace an entire image or a rectangular area of an image.
- Parameters
$image - the image to operate on
$startodd - set to false to get odd lines, true to get even lines (default: false)
$areax1 - start x value of rectangle (default: 0)
$areay1 - start y value of rectangle (default: 0)
$areax2 - end x value of rectangle (default: width of image)
$areay2 - end y value of rectangle (default: height of image)
<?php
function image_deinterlace(&$image, $startodd, $areax1 = 0, $areay1 = 0, $areax2 = -1, $areay2 = -1) {
if (!is_resource($image)) { return $image; }
if ($areax2 == -1) { $areax2 = imagesx($image); }
if ($areay2 == -1) { $areay2 = imagesy($image); }
if ($areax2 <= $areax1) { return $image; }
if ($areay2 - $areay1 < 2) { return $image; }
if ($startodd) {
for ($y = ($areay1 + 1); $y <= $areay2; $y = $y+2) {
for ($x = $areax1; $x <= $areax2; $x++) {
$curpixel = imagecolorat($image, $x, $y);
imagesetpixel($image, $x, $y - 1, $curpixel);
}
}
} else {
for ($y = $areay1; $y <= $areay2; $y = $y+2) {
for ($x = $areax1; $x <= $areax2; $x++) {
$curpixel = imagecolorat($image, $x, $y);
if ($y + 1 <= $areay2) {
imagesetpixel($image, $x, $y + 1, $curpixel);
}
}
}
}
return $image;
}
?>
twice 'kp0t' at google's mail dat com
22-Feb-2005 07:52
To Jon:
Thanks, you're probably right, and the readfile() function (for known-small-size files) is also on the list of viable options. I think it's all useful info in this section, since image caching-on-production is often a good practice.
foolish at noemail dot com
16-Feb-2005 06:16
@ k0pt: the best way to get a file to the client is with the img tag in html.
jon
14-Feb-2005 10:31
regarding kp0t's comment on using include() to return image data:
because include() looks for PHP code to process, using it to return binary data will eventually result in an error. some files will include the characters < ? followed by data that PHP will consider junk. much better to use fpassthru().
twice 'kp0t' at google's mail dat com
10-Feb-2005 01:13
If you're looking for a way to JUST SEND OUT AN IMAGE FILE (existing in your filesystem), you don't need GD (or any other extension) at all.
[GD may wrongly appear to beginners as the only or the preferred option. Well, this section DID confuse me.]
Correct me if I'm wrong, but something like the following will do perfectly well in this case (tested with PHP5):
<?php
header("Content-type: image/jpeg");
include("photo.jpg");
?>
That's looks like the most efficient way to get any (binary) file sent to the client's browser. Just don't forget to set the right header.
zuo_yf at yahoo dot com
05-Feb-2005 07:08
I wrote a class for easy to draw string on a picture.
you do only such as:
$string = $_GET['text'];
$img=new pullImage("image/bar13.png",
8,0,0,"12345678","png");
$img->setPaintColor(10,222,200);
$img->setPaintSize(8);
$img->setDrawText($string);
$img->DrawText();
here is the pullImage class:
class pullImage{
var $img_font_size=3;
var $origin_file_path="";
var $paint_color=array(0,0,0);
var $im=0;
var $poision_x=0;
var $poision_y=0;
var $poision_z=0;
var $pull_text="testing";
var $pull_image_type="png";
function pullImage($source_file_path="",$front_size=3,
$p_x=0,$p_y=0,$draw_text="png",$picture_type="png")
{
$this->img_font_size=$front_size;
$this->origin_file_path=$source_file_path;
$this->poision_x=$p_x;
$this->poision_y=$p_y;
$this->pull_image_type=$picture_type;
$this->pull_text=$draw_text;
}
function setPaintColor($red=0,$green=0,$blue=0)
{
$this->paint_color[0]=$red;
$this->paint_color[1]=$green;
$this->paint_color[2]=$blue;
}
function setPaintSize($fontsize)
{
$this->img_font_size=$fontsize;
}
function setImageType($type)
{
$this->pull_image_type=$type;
}
function setDrawText($txt)
{
$this->pull_text=$txt;
}
function DrawText()
{
$this->im=$this->createImgageFormFile();
if(!$this->im)
{
$this->responseError();
return;
}
$paint_color=$this->fill_solid_color($this->im);
$c_width = ImageFontWidth($this->img_font_size) * strlen($this->pull_text);
$c_height = ImageFontHeight($this->img_font_size);
$px = (imagesx($this->im) - $c_width) / 2;
$py = (imagesy($this->im)-$c_height)/2;
$this->pull_header();
imagestring($this->im, $this->img_font_size,
$px, $py, $this->pull_text, $paint_color);
$this->pull_Image($this->im);
imagedestroy($this->im);
}
function responseError()
{
echo("<p>Can't create image!</p>");
}
function pull_header()
{
switch(strtolower($this->pull_image_type))
{
case "png":
header("Content-type: image/png");
break;
case "jpg":
header("Content-type: image/jpeg");
break;
case "gif":
header("Content-type: image/gif");
default:
header("Content-type: image/png");
break;
}
}
function pull_Image($im)
{
if(!$im)return;
switch(strtolower($this->pull_image_type))
{
case "png":
@imagepng($im);
break;
case "jpg":
@imagejpeg($im);
break;
case "gif":
@imagegif($im);
default:
@imagepng($im);
break;
}
}
function createImgageFormFile()
{
$im=0;
if($this->origin_file_path=="")
return $im;
switch(strtolower($this->pull_image_type))
{
case "png":
$im=@imagecreatefrompng($this->origin_file_path);
break;
case "jpg":
$im=@imagecreatefromjpg($this->origin_file_path);
break;
case "gif":
$im=@imagecreatefromgif($this->origin_file_path);
default:
$im=@imagecreatefrompng($this->origin_file_path);
break;
}
if(!$im)
{
$im = @imagecreate (120, 40); /* Create a blank image */
$bgc = @imagecolorallocate ($im, 255, 255, 255);
@imagefilledrectangle ($im, 0, 0, 120, 40, $bgc);
}
return $im;
}
function fill_solid_color($im)
{
$ret=@imagecolorallocate($im,$this->paint_color[0],
$this->paint_color[1],$this->paint_color[2]);
return $ret;
}
}
shadikka at ihatespam dot gmail dot com
27-Jan-2005 07:42
Two stickfigures with different colors:
<?php
$img = imagecreatetruecolor(300,300);
$bgcol = imagecolorallocate($img,255,255,255);
$hatcol = imagecolorallocate($img,rand(128,255),rand(128,255),rand(128,255));
$headcol = imagecolorallocate($img,255,225,205);
$bodycol = imagecolorallocate($img,0,0,0);
$eyecol = imagecolorallocate($img,rand(100,200),rand(0,128),rand(128,255));
$mouthcol = imagecolorallocate($img,rand(128,255),0,0);
imagefill($img,0,0,$bgcol);
imagefilledellipse($img,60,71,50,50,$headcol);
imagefilledpolygon($img,array(30,53,60,23,90,53),3,$hatcol);
imagesetthickness($img,5);
imageline($img,60,97,60,201,$bodycol);
imagesetthickness($img,1);
imagefilledellipse($img,50,65,7,5,$eyecol);
imagefilledellipse($img,70,65,7,5,$eyecol);
imagesetthickness($img,8);
imageline($img,60,201,10,251,$bodycol);
imageline($img,60,201,110,251,$bodycol);
imageline($img,60,136,10,186,$bodycol);
imageline($img,60,136,110,186,$bodycol);
imagesetthickness($img,3);
imageline($img,50,80,60,90,$mouthcol);
imageline($img,60,90,70,80,$mouthcol);
$hatcol = imagecolorallocate($img,rand(128,255),rand(128,255),rand(128,255));
$headcol = imagecolorallocate($img,255,225,205);
$bodycol = imagecolorallocate($img,0,0,0);
$eyecol = imagecolorallocate($img,rand(100,200),rand(0,128),rand(128,255));
$mouthcol = imagecolorallocate($img,rand(128,255),0,0);
imagefilledellipse($img,200,71,50,50,$headcol);
imagefilledpolygon($img,array(170,53,200,23,230,53),3,$hatcol);
imagesetthickness($img,5);
imageline($img,200,97,200,201,$bodycol);
imagesetthickness($img,1);
imagefilledellipse($img,190,65,7,5,$eyecol);
imagefilledellipse($img,210,65,7,5,$eyecol);
imagesetthickness($img,8);
imageline($img,200,201,150,251,$bodycol);
imageline($img,200,201,250,251,$bodycol);
imageline($img,200,136,150,186,$bodycol);
imageline($img,200,136,250,186,$bodycol);
imagesetthickness($img,3);
imageline($img,190,80,200,90,$mouthcol);
imageline($img,200,90,210,80,$mouthcol);
imagestring($img,2,223,283,"(C) Shadikka",$bodycol);
imagesetthickness($img,1);
imagerectangle($img,0,0,299,299,$bodycol);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
I have used most basic image functions in the code.
carl at pappenheim dot net
20-Jan-2005 10:43
I notice that there is no pre-made function that is similar to Photoshop's 'trim' function. I appreciate this is very long-winded (a neater version would probably approach the centre in a sort of spiral movement) but at least it works and, hopefully, is clear.
The tolerance is effectively zero, and it takes the top left pixel (0,0) as being the background colour that is to be trimmed.
$filename = "image_with_white_border.jpg";
$image = imagecreatefromjpeg($filename);
if ($image) {
$dim = getimagesize($filename);
$backgnd = ImageColorAt($image,0,0);
for ($x=0;$x<$dim[0];$x++) {
for ($y=0;$y<$dim[1];$y++) {
if (ImageColorAt($image,$x,$y) != $backgnd) {
$trimx = $x; // found left edge
break(2);
}
}
}
for ($x=$dim[0];$x>=0;$x--) {
for ($y=0;$y<$dim[1];$y++) {
if (ImageColorAt($image,$x,$y) != $backgnd) {
$trimx2 = $x; // found right edge
break(2);
}
}
}
for ($y=0;$y<$dim[1];$y++) {
for ($x=0;$x<$dim[0];$x++) {
if (ImageColorAt($image,$x,$y) != $backgnd){
$trimy = $y; // found top edge
break(2);
}
}
}
for ($y=$dim[1];$y>=0;$y--) {
for ($x=0;$x<$dim[0];$x++) {
if (ImageColorAt($image,$x,$y) != $backgnd) {
$trimy2 = $y; // found bottom edge
break(2);
}
}
}
$trimxsize = $trimx2-$trimx; // calculate x dimension
$trimysize = $trimy2-$trimy; // calculate y dimension
$outimage = imagecreatetruecolor($trimxsize, $trimysize);
imagecopy($outimage, $image, 0,0, $trimx,$trimy, $trimxsize,$trimysize);
header('Content-type: image/jpeg');
imagejpeg($outimage, null, 100);
}
nick at IHATESPAM dot deceptykhan dot com
10-Jan-2005 06:10
Save yourself some head-whacking...Fedora Core 3's PHP does not come with GD enabled by default. For me, subsequent attempts to recompile PHP with GD (including zlib, libjpeg, libpng, etc.) failed harshly. To enable GD with as little as a headache as possible, simply install the php-gd-XXX.rpm (where XXX is your php version and platform, i.e. for me it was php-gd-4.3.10-3.2.i386.rpm - you can find it by searching 'php-gd' on rpmfind.net), restart Apache and take a look at your phpinfo(), you should see GD enabled. Voila!
dotpointer
05-Jan-2005 10:54
About PHP5 and imagejpeg, imagecreatefromjpeg being unknown when GD and libjpeg are installed on UNIX (Slackware).
You need to be sure that you have JPG Support on the server before you use these functions. Use phpinfo() and under the gd-section, see for "JPG Support: Enabled". If you can't see any line like that there, then you're missing support.
My problem was incorrect .configure-path to the libjpeg. I wrote --with-libjpeg-dir, instead of --with-jpeg-dir. Maybe old PHP4-syntax?
Also specifying exactly where libjpeg is located is good:
--with-jpeg-dir=/usr/lib/libjpeg.so.62
thc at forestfactory dot de
29-Nov-2004 01:53
Although there is allready one generic imagecreatfrom* function posted here, I will give you mine:
you may pass the $mime and $size variables by reference for further use (i.e. you can write the image in the original mime-type by settig a variable to "image$mime" and use it as a function). As the function is calling getimagesize() by itself, there is no need to do it again in your own source.
function imagecreatefromfile($file,&$mime,&$size) {
if (!$size = @getimagesize($file)) {
trigger_error("imagecreatefromfile($file): failed to open stream: No such file or directory ",E_USER_WARNING);
return false;
}
list($image,$mime) = explode("/",$size["mime"]);
$mime = strtolower($mime);
if (!function_exists("imagecreatefrom$mime")) {
trigger_error("imagecreatefromfile(): Mimetype (<i>$size[mime]</i>) is not supported by this version of GD",E_USER_WARNING);
return false;
}
$createStr = "imagecreatefrom$mime";
return $createStr($file);
}
neo-maximus at blueyonder dot co dot uk
24-Nov-2004 01:12
Create a user verification image like seen on sites like neopets. Now with encoded url image source for extra security...
file : image.php
<?php
require_once "encode.php";
$decid = urldecode(md5_decrypt($_REQUEST['id'], $_REQUEST['key']));
header("Content-type: image/png");
$img = imagecreatetruecolor(65, 20);
$white = imagecolorallocate($img, 255, 255, 255);
$brown = imagecolorallocate($img, 255, 51, 51);
imagefill($img, 0, 0, $brown);
imagestring($img, 3, 6, 3, $decid, $white);
imagepng($img, '', 75);
imagedestroy($img);
?>
file : encode.php (with thanks to a post on md5 section)
<?php
function get_rnd_iv($iv_len){
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
function md5_encrypt($plain_text, $password, $iv_len = 16){
$plain_text .= "\x13";
$n = strlen($plain_text);
if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = get_rnd_iv($iv_len);
$iv = substr($password ^ $enc_text, 0, 512);
while ($i < $n) {
$block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return base64_encode($enc_text);
}
function md5_decrypt($enc_text, $password, $iv_len = 16){
$enc_text = base64_decode($enc_text);
$n = strlen($enc_text);
$i = $iv_len;
$plain_text = '';
$iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
while ($i < $n) {
$block = substr($enc_text, $i, 16);
$plain_text .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}
?>
file : webform.php
with this file simply do your webform as you normally would and simply include the image into the file
i.e
<?php
require_once "encode.php";
$string = md5(rand(0, microtime()*1000000));
$verify_string = substr($string, 3, 7);
$key = md5(rand(0,999));
$encid = urlencode(md5_encrypt($verify_string, $key));
echo "<img src='1.php?id=$encid&key=$key'><br>";
echo "to verify the user would hve to type in $verify_string";
?>
Lost at LostLord dot com [Morteza Zafari]
08-Nov-2004 04:03
A simple image compare function.
It scans 2 images pixel by pixel, from left to right and from top to bottom, if all pixels have equal colors it will return 'True', otherwise it will return 'False'.
$img1 and $img2 must be of type image. (see usage)
----------------------------------------------
function imagecompare($img1, $img2) {
if (imagesx($img1)!=imagesx($img2) || imagesy($img1)!=imagesy($img2)){
return false;
}
for( $x=0; $x<imagesx($img1 ); $x++ ){
for ($y=0; $y<imagesy($img1); $y++) {
if(imagecolorat($img1,$x,$y)!=imagecolorat($img2,$x,$y)){
return false;
}
}
}
return true;
}
----------------------------------------------
Sample usage:
$im1=imagecreatefromgif("test1.gif");
$im2=imagecreatefromgif("test2.gif");
echo imagecompare(&$im1,&$im2);
andreaskalsch at gmx dot de
31-Oct-2004 08:18
These two are functions to flip an image (in true color)
- vertically:
function image_flip_vertical($im)
{
$x_i = imagesx($im);
$y_i = imagesy($im);
$im_ = imagecreatetruecolor($x_i, $y_i);
for ($x = 0; $x < $x_i; $x++)
{
for ($y = 0; $y < $y_i; $y++)
{
imagecopy($im_, $im, $x_i - $x - 1, $y, $x, $y, 1, 1);
}
}
return $im_;
}
- horizontally:
function image_flip_horizontal($im)
{
$x_i = imagesx($im);
$y_i = imagesy($im);
$im_ = imagecreatetruecolor($x_i, $y_i);
for ($x = 0; $x < $x_i; $x++)
{
for ($y = 0; $y < $y_i; $y++)
{
imagecopy($im_, $im, $x, $y_i - $y - 1, $x, $y, 1, 1);
}
}
return $im_;
}
I think there is no gd function to do the same.
orenivr at gmail dot com
27-Oct-2004 02:17
// create random image and chack if user insert the sam password
<?php
function get_rnd_iv($iv_len)
{
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
function md5_encrypt($plain_text, $password, $iv_len = 16)
{
$plain_text .= "\x13";
$n = strlen($plain_text);
if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = get_rnd_iv($iv_len);
$iv = substr($password ^ $enc_text, 0, 512);
while ($i < $n) {
$block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return base64_encode($enc_text);
}
function md5_decrypt($enc_text, $password, $iv_len = 16)
{
$enc_text = base64_decode($enc_text);
$n = strlen($enc_text);
$i = $iv_len;
$plain_text = '';
$iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
while ($i < $n) {
$block = substr($enc_text, $i, 16);
$plain_text .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}
function genpass($size = 6)
{
$possible = "0123456789QWERTYUIOPLKJHGFDSAZXCVBNM";
$string = "";
while ($i < $size) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function imgsecuregen($password)
{
$width = 11*6;
$height = 30;
$im = ImageCreate($width, $height);
$bg = imagecolorallocate($im, 200, 42, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$grey = imagecolorallocate($im, 90, 170, 220);
imagerectangle($im,0, 0, $width-1, $height-1, $grey);
imagestring($im, 5, $size, 5, $password, $black);
imagejpeg($im,"xx.jpg");
imagedestroy($im);
}
$key="HELLO WORLD";
if ((!$_POST["pasw"])||(!$_POST["valr"]))
{
$password = genpass();
imgsecuregen($password);
echo session_id();
$enc_text = md5_encrypt($password, $key);
echo "<img src='xx.jpg'> <br>
<FORM method='POST' target='_self'>
<INPUT TYPE='HIDDEN' name='pasw' value='$enc_text'>
<INPUT TYPE='TEXT' name='valr'>
<INPUT TYPE='SUBMIT' name='submit'>
</FORM> ";
}
else
{ $systemcode = $_POST["pasw"] ;
$userinsertcode = strtolower($_POST["valr"]) ;
$systemcode = strtolower(md5_decrypt($systemcode, $key));
$userinsertcode = str_replace("o","0",$userinsertcode);
$systemcode = str_replace("o","0",$systemcode);
if ($systemcode == $userinsertcode) print ($systemcode); else print ("Error in image code ");
}
?>
phpm at nreynolds dot me dot uk
11-Oct-2004 07:48
A generic image loading function, determines the file format by itself.
<?php
function imagecreatefromfile($filename)
{
static $image_creators;
if (!isset($image_creators)) {
$image_creators = array(
1 => "imagecreatefromgif",
2 => "imagecreatefromjpeg",
3 => "imagecreatefrompng",
16 => "imagecreatefromxbm"
);
}
$image_size = getimagesize($filename);
if (is_array($image_size)) {
$file_type = $image_size[2];
if (isset($image_creators[$file_type])) {
$image_creator = $image_creators[$file_type];
if (function_exists($image_creator)) {
return $image_creator($filename);
}
}
}
return "";
}
?>
andreoli dot carlo at libero dot it
31-Aug-2004 10:17
Here my compact gradient function (request few passage):
function imagecolorgradient($img,$x1,$y1,$height,$width,$colA,$colB) {
$varC1=($colA[1]-$colB[1])/$height;
$varC2=($colA[2]-$colB[2])/$height;
$varC3=($colA[3]-$colB[3])/$height;
for ($i=0;$i<=$height;$i++) {
$red=$colA[1]-floor($i*$varC1);
$green=$colA[2]-floor($i*$varC2);
$blue=$colA[3]-floor($i*$varC3);
$col= ImageColorAllocate($img,$red,$green,$blue);
ImageLine($img,$x1,$y1+$i,$x1+$width,$y1+$i,$col);
}
}
even more compact mode:
function imagecolorgradient($img,$x1,$y1,$height,$width,$colA,$colB) {
$varC1=($colA[1]-$colB[1])/$height;
$varC2=($colA[2]-$colB[2])/$height;
$varC3=($colA[3]-$colB[3])/$height;
for ($i=0;$i<=$height;$i++) {
$col=ImageColorAllocate($img,
$colA[1]-floor($i*$varC1),
$colA[2]-floor($i*$varC2),
$colA[3]-floor($i*$varC3));
ImageLine($img,$x1,$y1+$i,$x1+$width,$y1+$i,$col);
}
}
$img ist the image handle,
$x1 and $y1 are the start points,
$height is the gradient height, $width the width,
$colA and $colB are the first and second color ARRAYs.
Henrik Nyh
22-Aug-2004 07:05
I modified the gradient rectangle function by info [@] solanki [d o t] ch, to use hexadecimal colours instead of arrays.
The hex-to-RGB code was taken from a comment by "tim at phantomrpg dot com" at
<?php
function imagecolorgradient($img,$x1,$y1,$x2,$y2,$f_c,$s_c){
sscanf($f_c, "%2x%2x%2x", $red, $green, $blue);
$f_c = array($red,$green,$blue);
sscanf($s_c, "%2x%2x%2x", $red, $green, $blue);
$s_c = array($red,$green,$blue);
if($y2>$y1) $y=$y2-$y1;
else $y=$y1-$y2;
if($f_c[0]>$s_c[0]) $r_range=$f_c[0]-$s_c[0];
else $r_range=$s_c[0]-$f_c[0];
if($f_c[1]>$s_c[1]) $g_range=$f_c[1]-$s_c[1];
else $g_range=$s_c[1]-$f_c[1];
if($f_c[2]>$s_c[2]) $b_range=$f_c[2]-$s_c[2];
else $b_range=$s_c[2]-$f_c[2];
$r_px=$r_range/$y;
$g_px=$g_range/$y;
$b_px=$b_range/$y;
$r=$f_c[0];
$g=$f_c[1];
$b=$f_c[2];
for($i=0;$i<=$y;$i++){
$col=imagecolorallocate($img,round($r),round($g),round($b));
imageline($img,$x1,$y1+$i,$x2,$y1+$i,$col);
if($f_c[0]<$s_c[0]) $r+=$r_px;
else $r-=$r_px;
if($f_c[1]<$s_c[1]) $g+=$g_px;
else $g-=$g_px;
if($f_c[2]<$s_c[2]) $b+=$b_px;
else $b-=$b_px;
}
return $img;
}
?>
Usage example:
<?php
imagecolorgradient($image,0,0,50,50,'000000','FFFFFF');
?>
Caleb Simonyi-Gindele
01-Jul-2004 02:02
What a pain! finally got GD/PHP working 100%. I was not getting jpeg support.
What I ended up doing was installing the jpeg-v6b library with the --enable-shared on the ./configure prompt. Then over to php folder and did a configure as follows:
./configure --with-apxs2=/usr/local/apache2/bin/apxs --enable-exif --with-gd --with-jpeg --with-jpeg-dir=/usr/local/lib --with-tiff-dir=/usr/lib --with-png-dir=/usr/lib --with-pgsql=/usr/local/pgsql --enable-track-vars --with-xml --with-zlib-dir=/usr/local/lib
then make clean
then make
then make install
restart my Apache service. FYI, I'm on RH 7, php 4.3.7 and apache 2.0.49
Hope that helps somebody cause it took me all afternoon to get jpeg support!
Bren
21-Jun-2004 04:00
Sometimes getting GD to work may require that you look at the makefile after running ./configure.
If you are attempting to configure php with --with-jpeg-dir=!location! or with-png-dir=!location! I've found that the configure script (under some unix builds) doesn't output the correct makefile as it doesn't place the actual location in and thus you get "libjpeg.h - no such file or directory"
you can check that though by opening the makefile in your fav. editor and ensure lines like:
GDLIB_CFLAGS = -I/<phpsourcedir>/ext/gd/libgd -DHAVE_LIBPNG -DHAVE_LIBJPEG
read as
GDLIB_CFLAGS = -I/<phpsourcedir>/ext/gd/libgd -DHAVE_LIBPNG -DHAVE_LIBJPEG -I/<jpegsourcedir>/jpeg-6b
where <jpegsourcedir> and <phpsourcedir> are your equivilent directories.
running make will then find the libraries it needs and you should be running.
purplebz at hotmail dot com
12-Apr-2004 05:47
Installing GD extension on Windows:
First you need to download PHP 4.3.x zip package not the PHP 4.3.x installer! PHP 4.3.x zip package has extensions included already.
Follow the instructions on installing PHP at install.text.
If PHP is already working, you may now activate the GD by doing the following:
1. Uncomment the - extension_dir="". Then you should point it to where the extensions folder is located. Extensions folder is extracted from PHP zip file you downloaded.
Example: extension_dir = C:/PHP/extensions
2. Uncomment the following by removing the semicolon -
Example: extension=php_gd2.dll
3. Test if GD extension is already loaded by executing the following lines:
<?php
var_dump(gd_info());
?>
Hope this helps!
info [@] solanki [d o t] ch
14-Feb-2004 05:43
A quite important function missing in the gdlib ist the color gradient.
After trying a bit I got one that works quite good.
So if anybody needs it:
<?php
function imagecolorgradient($img,$x1,$y1,$x2,$y2,$f_c,$s_c){
if($y2>$y1) $y=$y2-$y1;
else $y=$y1-$y2;
if($f_c[0]>$s_c[0]) $r_range=$f_c[0]-$s_c[0];
else $r_range=$s_c[0]-$f_c[0];
if($f_c[1]>$s_c[1]) $g_range=$f_c[1]-$s_c[1];
else $g_range=$s_c[1]-$f_c[1];
if($f_c[2]>$s_c[2]) $b_range=$f_c[2]-$s_c[2];
else $b_range=$s_c[2]-$f_c[2];
$r_px=$r_range/$y;
$g_px=$g_range/$y;
$b_px=$b_range/$y;
$r=$f_c[0];
$g=$f_c[1];
$b=$f_c[2];
for($i=0;$i<=$y;$i++){
$col=imagecolorallocate($img,round($r),round($g),round($b));
imageline($img,$x1,$y1+$i,$x2,$y1+$i,$col);
if($f_c[0]<$s_c[0]) $r+=$r_px;
else $r-=$r_px;
if($f_c[1]<$s_c[1]) $g+=$g_px;
else $g-=$g_px;
if($f_c[2]<$s_c[2]) $b+=$b_px;
else $b-=$b_px;
}
return $img;
}
?>
$img ist the image handle, $x1 and $y1 are the start points, $x2 and $y2 the ending points.
$f_c and $s_c are the first and second color ARRAYs.
jeff at lushmedia dot com
04-Nov-2003 04: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
daniel @ swn
17-Sep-2003 02:55
For everyone trying to get jpeg support working:
Since I could not compile jpeg support with the bundled gd library in php 4.3.3, I tried with the external one and got some reference errors. If you get these errors when make'ing PHP, try to set the XPM directory when configuring gd2. I noticed that there are some error messages when compiling php with the default xpm setting in gd2's configure. Maybe there is something similar concerning freetype support, too...so I activated it however I need it or not.
What I did:
I downloaded and installed jpeg6b, freetype etc.:
./configure
make
make install
downloaded xpm and copied any files and directories to /usr/local
downloaded gd2 and installed it..
./configure --with-jpeg=/usr/local --with-freetype=/usr/local --with-png=/usr/local --with-xpm=/usr/local
[make clean]
make
make install
and when configuring gd2 told me that it could not compile xpm support. Maybe I did something wrong but now the php 'make' runs without errors:
./configure [...] --with-gd=/usr/local --with-jpeg-dir=/usr/local
make
make install
and the jpeg functions started to work...
da_linuxguru at NOSPAM dot hotmail dot com
11-Sep-2003 11:35
Installing Php with GD support
Packages Needed:
GD
zlib
libjpeg-6b
Php
Installing GD
a) ./configure
b) gmake, gmake install
Installing Zlib
a) ./configure --shared
b) gmake, gmake install
Installing Libjpeg-6b
a) ./configure --enable-shared
b) gmake, gmake install
Assuming your apache installation is in the directory /www
Installing Php
./configure --with-apxs2=/www/bin/apxs --with-mysql --prefix=/www/php --with-config-file-path=/www/php --enable-track-vars --disable-cgi --with-gd=/usr/local --with-jpeg-dir=/usr/local
Finally, I had problems while compiling php ver 4.3.2 and 4.3.3 bot with the same problem related to a function in the file phpsourcedir/ext/gd/gd.c called Imagecache seomthing... I had to comment this line and then all went fine, however the tumbnails that I am still gettting are 256 colors only.
-Dhaval
pigmeu at pigmeu dot net
02-Sep-2003 07:09
I had some troubles when trying to resize an image gotten from a database blob field... Perhaps that these image functions don't work with opened image streams...
So, I had to make this workaround...
Use this code if you are trying to handle imagens from a database.
//...
// creating a temp image name
$t_img_name = tempnam ("/tmp", "timg");
$t_img = fopen($t_img_name, "w");
// $content is the blob field with the image.
fwrite($t_img, $content);
fclose($t_img);
// now, do what want to with the image
$size = getimagesize($t_img_name);
echo $size[0]." - ".$size[1];
// don't forget to delete the temp file after all.
unlink($t_img_name);
//...
sameerni at netscape dot net
19-Aug-2003 07:30
i tried to install gd on linux (RedHat 8.0) with apache 1.3.27 and php 4.3.2
i had libjpeg, libz, libgif, libpng, libgd installed in /usr/lib.
i compiled php using following ./configure command:
./configure --prefix=/usr/local/php --with-apxs=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql --with-gd --with-gd-dir=/usr/lib --with-freetype --with-freetype-dir=/usr/lib --enable-ftp --with-jpeg --with-jpeg-dir=/usr/lib --with-png --with-png-dir=/usr/lib --with-gif --with-gif-dir=/usr/lib --with-xml --with-xslt --with-zlib --with-zlib-dir=/usr/lib
it compiled without any problem. but phpinfo() did not show jpeg support.
and it did not find imagecreatefromjpeg() so i installed libjpeg-6b in different directory (in /usr/lib/jpeg6b) and recompiled php with following command.
./configure --prefix=/usr/local/php --with-apxs=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql --with-gd --with-gd-dir=/usr/lib --with-freetype --with-freetype-dir=/usr/lib --enable-ftp --with-jpeg --with-jpeg-dir=/usr/lib/jpeg6b --with-png --with-png-dir=/usr/lib --with-gif --with-gif-dir=/usr/lib --with-xml --with-xslt --with-zlib --with-zlib-dir=/usr/lib
and imagecreatefromjpeg() started working.
also phpinfo() shows jpg support enabled.
----------output of phpinfo()-------------
[snip]
gd
GD Support enabled
GD Version bundled (2.0.12 compatible)
FreeType Support enabled
FreeType Linkage with freetype
GIF Read Support enabled
JPG Support enabled
PNG Support enabled
WBMP Support enabled
XBM Support enabled
[snip]
----------output of phpinfo()-------------
hope you will find this useful.
office at 4point-webdesign dot com
06-Jul-2003 09:29
Here's a funtion i used to resize and save images uploaded by the user, you can either create thumbnails or other images.
Main "feature" is that the width and height stay relativ to each other.
imgcomp is the quality, i turned it around so now its from 0 -best to 100 -most compressed.
For gif version just change the functions names.
function resampimagejpg($forcedwidth, $forcedheight, $sourcefile, $destfile, $imgcomp)
{
$g_imgcomp=100-$imgcomp;
$g_srcfile=$sourcefile;
$g_dstfile=$destfile;
$g_fw=$forcedwidth;
$g_fh=$forcedheight;
if(file_exists($g_srcfile))
{
$g_is=getimagesize($g_srcfile);
if(($g_is[0]-$g_fw)>=($g_is[1]-$g_fh))
{
$g_iw=$g_fw;
$g_ih=($g_fw/$g_is[0])*$g_is[1];
}
else
{
$g_ih=$g_fh;
$g_iw=($g_ih/$g_is[1])*$g_is[0];
}
$img_src=imagecreatefromjpeg($g_srcfile);
$img_dst=imagecreate($g_iw,$g_ih);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);
imagejpeg($img_dst, $g_dstfile, $g_imgcomp);
imagedestroy($img_dst);
return true;
}
else
return false;
}
dehumanizer at optusnet dot com dot au
31-May-2003 01:18
If you are trying to install jpeg support with php, then first install jpeg-6b and libpng. And when starting to install gd, check out the Makefile. I tried to install gd-1.8.4 and found that the Makefile didnt include the jpeglibs, rather all were commented. Uncomment the lines where you'll find the JPEG libs are mentioned. Like the lines below:
CFLAGS=-0 -DHAVE_LIBPNG -DHAVE_LIBJPEG
CFLAGS=-0 -DHAVE_LIBXPM -DHAVE_LIBPNG -DHAVE_LIBJPEG
There are several lines like that those you have to uncomment. Now install gd.
Before installing php, check if there is any config.cache file existing. If it does, delete it. The php ./configure sysntax should have --with-jpeg-dir --with-png-dir --with-gd=/path/to/gd
After configure is done, check out the config.cache file. If jpeg and png supports are installed successfully, you should be able to find these lines:
ac_cv_lib_gd_gdImageCreateFromJpeg=
${ac_cv_lib_gd_gdImageCreateFromJpeg=yes}
ac_cv_lib_gd_gdImageCreateFromPng=
${ac_cv_lib_gd_gdImageCreateFromPng=yes}
now, make and make install.
I put all the installers in one directory. So, this is how my dir-structure looked like
/opt/apache/download/upgrade/apache_1.3.27
/opt/apache/download/upgrade/gd-1.8.4
/opt/apache/download/upgrade/jpeg-6b
/opt/apache/download/upgrade/libpng-1.2.5
/opt/apache/download/upgrade/php-4.2.3
No directory prefix was used while configuring gd/jpeg/libpng/
This worked for me pretty fine. Hope this will help and save time for someone.
sellout at NoSpAm dot dharmadevil dot com
16-Apr-2003 05: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';
if ( strlen($code) != 11 ) { die("UPC-A Must be 11 digits."); }
$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;
$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;
$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);
}
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);
header("Content-Type: image/png");
ImagePNG($img);
}
UPCAbarcode('12345678901');
?>
Angus Chung a swinburnemultimediastudent
03-Apr-2003 06:40
this code work faster in my p4 2G machine PHP Version 4.3.1 imageresampled() gives better quality however much slower when work on high resolution image , e.g. the DC photo.therefore i first use imageresized() to produce a middle size temp image, then imageresampled() the temp image to a smaller thumbnail and output to the browser
<?php
$t_w = 444; $t_h = 333; ................
................
imagecopyresized ($destimage,$srcimage,0,0,0,0,$t_w,$t_h,$width,$height);
$t_w2 = round($t_w/3); $t_h2 = round($t_h/3); $destimage2 = imagecreatetruecolor($t_w2,$t_h2); imagecopyresampled ($destimage2,$destimage,0,0,0,0,$t_w2,$t_h2,$t_w,$t_h);
imagedestroy($destimage);
imageinterlace ($destimage2,1);imagejpeg($destimage2, '', 45);
imagedestroy($destimage2);
.................
?>
RJ-Gerry at wiu dot edu
07-Mar-2003 08:00
I have successfully installed GD and FreeType 2 with PHP 4.3.0 on my OS X 10.2.4 (Jaguar) machine. Using fink which comes with dselect (a menu � based apt-get), I was able to download and install both GD and FreeType 2 without having to compile either one of them. I was then able to add them into PHP by using this configure command (and then make and make install of course):
./configure --with-mysql --with-apxs --with-gd=/sw --with-freetype-dir=/sw --with-ttf
The directories for gd and freetype were both /sw because that is where fink installs its software. I also added the �-with-ttf to make sure that True Type Fonts were supported. Hope this helps any OS X users!
khyri at idyllmtn dot com
06-Mar-2003 07:00
To save others the hours I spent, I'd like to point out the
following:
Even if you are using the built-in GD libraries for 4.3.0 and
above, you still need to download and install jpeg-6b, libpng
and zlib before you can manipulate anything except read-only
gifs. These libraries are NOT bundled.
And they need to be installed as shared, not static libraries.
The default installation for jpeg-6b will only make a static
library (do ./configure --enabled-shared) and the selection
of makefile for libpng will determine whether you end up with
a shared or static library.
cysoft at php dot net
05-Mar-2003 04:32
How to using GD out put chinese Characters (BIG 5 or GB2312).
the following code shows you how to using gd display chinese Characters.
there is a funcation called by ImageTTFText.
since gd dose not support GB2312/big5 but unicode.if you can convert
Characters to unicode which you want display then every thing will be done!
your 's yan
<?php
function gb23122uni($text) {
$rtext="";
$max=strlen($text);
for($i=0;$i<$max;$i++){
$h=ord($text[$i]);
if($h>=160 && $i<$max-1){
$rtext.="&#".base_convert(bin2hex(iconv("gb2312","ucs-2",
substr($text,$i,2))),16,10).";";
$i++;
}else{
$rtext.=$text[$i];
}
}
return $rtext;
}
Header("Content-type: image/gif");
$im = imagecreate(400,50);
$black = ImageColorAllocate($im, 0,255,0);
$white = ImageColorAllocate($im, 255,0,255);
ImageTTFText($im, 20, 0, 30, 30, $white, "c:\php\STCAIYUN.ttf",gb23122uni("
���")."test");
Imagejpeg($im);
ImageDestroy($im);
?>
sir_hmba at NOSPAMyahoo dot com
17-Jan-2003 06:13
The GD library, prior to 2.x, does not appear to process images with more than 256 colors without first converting them to a 256 color indexed (palette) image.
In other words, if you have a truecolor JPEG or PNG and you load the image up with these functions (e.g., imagecreatefrompng()) then the internal resource will be a palettized version of your original. The only information I found about this were in a few separate comments spread around this section.
If you compile PHP with a 2.0 or higher version of the GD library, then the internal image resource will not be subjected to this automatic conversion. I believe that all the RedHat PHP RPMs (as of today) still come compiled with the older version of GD (pre 2.0).
dbonomo at 3drealm dot net
27-Dec-2002 01:01
This may be a known thing among the more experienced programmers here, but a basic piece of information needed to allow you to include a php-generated image in a page with other content is that you treat it as if it were an image. Here is an example of what I mean:
<img src=filename.php?var1=val1&var2=val2>
In the above example filename.php is the php file that has all the image generation code.
The php you write to create the picture is essentially a picture itself, and needs to be treated as such. Maybe Im being thick, but it took a couple of days of hammering away at it to be able to mix php-generated images with the rest of the page's content.
I am so far very impressed with how straightforward this all is. I have been avoiding this aspect of the code but now I love it.
Hope this helps.
Doug Bonomo
webmaster at wutallan dot net
13-Dec-2002 07:47
Installing PHP with GD2 support on a system running Debian Woody is quite easy. You just need to install the deb packages of the libs, including the -dev packages. Do this with one apt-get command:
apt-get install libgd2 libgd2-dev libjpeg62 libjpeg62-dev libpng2 libpng2-dev libfreetype6 libfreetype6-dev
(libpng depends on zlib, so it will automatically be installed)
Having those libs installed, add this to your PHP configure command:
--with-gd --with-jpeg-dir=/usr/lib --with-png-dir=/usr/lib --with-freetype-dir=/usr/lib --with-zlib-dir=/usr/lib
stefan dot wehowsky at profilschmiede dot de
02-Feb-2002 11:57
If you ever want to resize a picture (maybe in order to create a thumbnail), this small function
should help you. It also gives you an idea of how some of the basic image functions of PHP can be
used.
/* resizeToFile resizes a picture and writes it to the harddisk
*
* $sourcefile = the filename of the picture that is going to be resized
* $dest_x = X-Size of the target picture in pixels
* $dest_y = Y-Size of the target picture in pixels
* $targetfile = The name under which the resized picture will be stored
* $jpegqual = The Compression-Rate that is to be used
*/
function resizeToFile ($sourcefile, $dest_x, $dest_y, $targetfile, $jpegqual)
{
/* Get the dimensions of the source picture */
$picsize=getimagesize("$sourcefile");
$source_x = $picsize[0];
$source_y = $picsize[1];
$source_id = imageCreateFromJPEG("$sourcefile");
/* Create a new image object (not neccessarily true colour) */
$target_id=imagecreatetruecolor($dest_x, $dest_y);
/* Resize the original picture and copy it into the just created image
object. Because of the lack of space I had to wrap the parameters to
several lines. I recommend putting them in one line in order keep your
code clean and readable */
$target_pic=imagecopyresampled($target_id,$source_id,
0,0,0,0,
$dest_x,$dest_y,
$source_x,$source_y);
/* Create a jpeg with the quality of "$jpegqual" out of the
image object "$target_pic".
This will be saved as $targetfile */
imagejpeg ($target_id,"$targetfile",$jpegqual);
return true;
}
npdavis at hotmail dot com
24-May-2001 05:45
I build menus using image functions. I noticed that even if you preload the images, some do not always load. In addition the image generation puts a load on the server... the answer? Cache Control headers. These headers will cause IE and Netscape to load all images correctly and also force the proxys and web caches to cache them, allowing your pages to render correctly, AND save you lots of cycles: ) These headers tell both the browser and the ISP caches/proxys to cache the images.
Here is the code:
Header ("Last-Modified: " . gmdate("D, d M Y H:i:s",mktime (0,0,0,1,1,2000)) . " GMT"); // Date in the past
Header ("Expires: Mon, 26 Jul 2040 05:00:00 GMT"); // In other words... never expire the image
Header ("Cache-Control: max-age=10000000, s-maxage=1000000, proxy-revalidate, must-revalidate");//Cache-Control header is ESSENTIAL for forcing Netscape to load all images!... and telling the ISP caches to do the same in this case cache for 1 million seconds.
These headers may or may not be redundant... any input is welcome.
In addition, it is essential for proxys and ISP caches that your re-used images have the same url... IE create a generic image creation script, and feed it parameters. This way your
Home link image has the same url on all of your pages... This will make your images more proxy/cacheserver cache AND browser cache friendly.
thx,
Neil
leefelix at pacific dot net dot hk
12-Mar-2001 06:12
For those of you who wants to compile PHP as Apache static module but failed in compiling Apache (undefined some PNG_XXX) functions, try re-ordering the -l parameters in Apache Makefiles (there are several) so that "-lgd is loaded before -lpng".
07-Mar-2001 07:29
When using ImageGif( $im ) it sends the output directly to the browser. to prevent this from happening and also to be able to save your new image to a database for example use ob_start(), ob_get_contents(), and ob_end_clean() <BR><BR>ex:<BR> <?php <BR>function ResizeGif( $image, $newWidth, $newHeight){
$srcImage = ImageCreateFromGif( $image );
$srcWidth = ImageSX( $srcImage );
$srcHeight = ImageSY( $srcImage );
if( $srcWidth < $srcHeight ){
$destWidth = $newWidth * $srcWidth/$srcHeight;
$destHeight = $newHeight;
}else{
$destWidth = $newWidth;
$destHeight = $newHeight * $srcHeight/$srcWidth;
}
$destImage = imagecreate( $destWidth, $destHeight);
ImageCopyResized( $destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight );
ImageGif( $destImage );
ImageDestroy( $srcImage );
ImageDestroy( $destImage );
}
ob_start();
ResizeGif( "/where/image/is/image.gif", "150", "150");
$resizedImage = ob_get_contents();
ob_end_clean();
| |