to troy and henry:
not $fontpath='../../../WINDOWS/fonts/';
but $fontpath = 'C:/Windows/fonts/';
its more likely to work with everyone on a windows.
Fonctions GD
Sommaire
- gd_info — Retourne des informations à propos de la bibliothèque GD installée
- getimagesize — Retourne la taille d'une image
- image_type_to_extension — Retourne l'extension du fichier pour le type d'image
- image_type_to_mime_type — Lit le Mime-Type d'un type d'image
- image2wbmp — Crée une image WBMP
- imagealphablending — Modifie le mode de blending d'une image
- imageantialias — Utiliser ou non les fonctions d'antialias
- imagearc — Dessine une ellipse partielle
- imagechar — Dessine un caractère horizontalement
- imagecharup — Dessine un caractère verticalement
- imagecolorallocate — Alloue une couleur pour une image
- imagecolorallocatealpha — Alloue une couleur à une image
- imagecolorat — Retourne l'index de la couleur d'un pixel donné
- imagecolorclosest — Retourne l'index de la couleur la plus proche d'une couleur donnée
- imagecolorclosestalpha — Retourne la couleur la plus proche, en tenant compte du canal alpha
- imagecolorclosesthwb — Lit l'index de la couleur spécifiée avec sa teinte, blanc et noir
- imagecolordeallocate — Supprime une couleur d'une image
- imagecolorexact — Retourne l'index de la couleur donnée
- imagecolorexactalpha — Retourne l'index d'une couleur avec son canal alpha
- imagecolormatch — Fait correspondre un peu plus les couleurs de la version palette d'une image aux couleurs de sa version truecolor
- imagecolorresolve — Retourne l'index de la couleur donnée, ou la plus proche possible
- imagecolorresolvealpha — Retourne un index de couleur ou son alternative la plus proche, y compris le canal alpha
- imagecolorset — Change la couleur dans une palette à l'index donné
- imagecolorsforindex — Retourne la couleur associée à un index
- imagecolorstotal — Calcule le nombre de couleurs d'une palette
- imagecolortransparent — Définit la couleur transparente
- imageconvolution — Applique une matrice de la convolution 3x3, en utilisant le coefficient et l'excentrage
- imagecopy — Copie une partie d'une image
- imagecopymerge — Copie et fusionne une partie d'une image
- imagecopymergegray — Copie et fusionne une partie d'une image en niveaux de gris
- imagecopyresampled — Copie, redimensionne, rééchantillonne une image
- imagecopyresized — Copie et redimensionne une partie d'une image
- imagecreate — Crée une nouvelle image à palette
- imagecreatefromgd2 — Crée une nouvelle image à partir d'un fichier GD2 ou d'une URL
- imagecreatefromgd2part — Crée une nouvelle image à partir d'une partie de fichier GD2 ou d'une URL
- imagecreatefromgd — Crée une nouvelle image à partir d'un fichier GD ou d'une URL
- imagecreatefromgif — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatefromjpeg — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatefrompng — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatefromstring — Crée une image à partir d'une chaîne
- imagecreatefromwbmp — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatefromxbm — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatefromxpm — Crée une nouvelle image à partir d'un fichier ou d'une URL
- imagecreatetruecolor — Crée une nouvelle image en couleurs vraies
- imagedashedline — Dessine une ligne pointillée
- imagedestroy — Détruit une image
- imageellipse — Dessine une ellipse
- imagefill — Remplissage
- imagefilledarc — Dessine une ellipse partielle et la remplit
- imagefilledellipse — Dessine une ellipse pleine
- imagefilledpolygon — Dessine un polygone rempli
- imagefilledrectangle — Dessine un rectangle rempli
- imagefilltoborder — Remplit une région avec une couleur spécifique
- imagefilter — Applique un filtre à une image
- imagefontheight — Retourne la hauteur de la police
- imagefontwidth — Retourne la largeur de la police
- imageftbbox — Calcule le rectangle d'encadrement pour un texte, en utilisant la police courante et freetype2
- imagefttext — Écrit du texte dans une image avec la police courante FreeType 2
- imagegammacorrect — Applique une correction gamma à l'image GD
- imagegd2 — Génère une image au format GD2, vers le navigateur ou un fichier
- imagegd — Génère une image au format GD, vers le navigateur ou un fichier
- imagegif — Envoie une image GIF vers un navigateur ou un fichier
- imagegrabscreen — Capture l'écran complet
- imagegrabwindow — Capture une fenêtre
- imageinterlace — Active ou désactive l'entrelacement
- imageistruecolor — Détermine si une image est une image truecolor
- imagejpeg — Envoie une image JPEG vers un navigateur ou un fichier
- imagelayereffect — Active l'option d'alpha blending, pour utiliser les effets de libgd
- imageline — Dessine une ligne
- imageloadfont — Charge une nouvelle police
- imagepalettecopy — Copie la palette d'une image à l'autre
- imagepng — Envoie une image PNG vers un navigateur ou un fichier
- imagepolygon — Dessine un polygone
- imagepsbbox — Retourne le rectangle entourant un texte et dessiné avec une police PostScript Type1
- imagepsencodefont — Change le codage vectoriel d'un caractère dans une police
- imagepsextendfont — Étend ou condense une police de caractères
- imagepsfreefont — Libère la mémoire occupée par une police PostScript Type 1
- imagepsloadfont — Charge une police PostScript Type 1 depuis un fichier
- imagepsslantfont — Incline une police de caractères PostScript
- imagepstext — Dessine un texte sur une image avec une police PostScript Type1
- imagerectangle — Dessine un rectangle
- imagerotate — Fait tourner une image d'un angle
- imagesavealpha — Configure l'enregistrement des informations complètes du canal alpha lors de sauvegardes d'images PNG
- imagesetbrush — Modifie la brosse pour le dessin des lignes
- imagesetpixel — Dessine un pixel
- imagesetstyle — Configure le style pour le dessin des lignes
- imagesetthickness — Modifie l'épaisseur d'un trait
- imagesettile — Modifie l'image utilisée pour le carrelage
- imagestring — Dessine une chaîne horizontale
- imagestringup — Dessine une chaîne verticale
- imagesx — Retourne la largeur d'une image
- imagesy — Retourne la hauteur de l'image
- imagetruecolortopalette — Convertit une image en couleurs vraies en image à palette
- imagettfbbox — Retourne le rectangle entourant un texte et dessiné avec une police TrueType
- imagettftext — Dessine un texte avec une police TrueType
- imagetypes — Retourne les types d'images supportés par la version courante de PHP
- imagewbmp — Affiche une image WBMP
- imagexbm — Génère une image au format XBM
- iptcembed — Intègre des données binaires IPTC dans une image JPEG
- iptcparse — Analyse un bloc binaire IPTC et recherche les balises simples
- jpeg2wbmp — Convertit une image JPEG en image WBMP
- png2wbmp — Convertit une image PNG en image WBMP
Fonctions GD
bryan dot spirit at gmail dot com
08-Jun-2008 05:40
08-Jun-2008 05:40
dev at kingthief dot com
29-Mar-2008 12:20
29-Mar-2008 12: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!
henry at corpocuisine dot com
17-Mar-2008 08:39
17-Mar-2008 08:39
To troy,
Good demo of GD "tricks"
If safe mode is not: on;
then it will be better to:
instead of using putenv()
using the following which will work in any php.ini settings environment.
$fontpath='../../../WINDOWS/fonts/';
$font =$fontpath. 'arial.ttf';
troy --at-- goemr.com
15-Mar-2008 06:09
15-Mar-2008 06:09
Here is a fun example Easter Egg drawing that uses a bunch of image functions. Just in time for Easter 2008. Enjoy.
<?php
$image = imagecreatetruecolor(400, 500);
$bg = imagecolorallocate($image, 10, 10, 150);
imagefill($image, 0, 0, $bg);
// allocate some colors
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image, 0, 0, 0);
// choose a color for the elipse
$col_ellipse = imagecolorallocate($image, 255, 200, 255);
// draw ellipse shadow
imagefilledellipse($image, 215, 265, 320, 400, $black);
// draw the ellipse
imagefilledellipse($image, 200, 250, 320, 400, $col_ellipse);
//draw arc where plastic egg opens
imagearc($image, 198, 235, 326, 100, 0, 180, $bg);
$colour = imagecolorallocate($image, 100, 0, 200);
$ca = rand(2,5);
$cb = rand(2,5);
$cc = rand(2,5);
$cd = rand(2,5);
${"colour".$ca} = imagecolorallocate($image, 153, 204, 255);
${"colour".$cb} = imagecolorallocate($image, 102, 0, 153);
${"colour".$cc} = imagecolorallocate($image, 204, 153, 204);
${"colour".$cd} = imagecolorallocate($image, 153, 0, 255);
//positions of stars relative to original position
$shift['x'][]=0; //star 1
$shift['y'][]=0;
$star['color'][] = $colour;
$shift['x'][]=-80; //star 2
$shift['y'][]=-120;
$star['color'][] = $colour2;
$shift['x'][]=-130; //star 3
$shift['y'][]=10;
$star['color'][] = $colour3;
$shift['x'][]=-10; //star 4
$shift['y'][]=-250;
$star['color'][] = $colour4;
$shift['x'][]=-160; //star 5
$shift['y'][]=-200;
$star['color'][] = $colour5;
for($ii=0; $ii < count($shift['x']); $ii++)
{
// set up array of points for polygon
$values = array(
230, 330,
290, 390,
280, 340,
240, 380,
310, 370,
230, 330
);
$shiftX = $shift['x'][$ii];
$shiftY = $shift['y'][$ii];
foreach ($values as &$val)
{
if($i == 1){ $val = $val+$shiftY; $i++; }
else
{ $val = $val+$shiftX; $i = 1; }
}
// draw a star filled in with a circle
imagefilledpolygon($image, $values, 6, $star['color'][$ii]);
imagefilledellipse($image, 273+$shiftX, 364+$shiftY, 35, 24, $star['color'][$ii]);
}//end for
// Rotate
$degrees = rand(0,360);
$image= imagerotate($image, $degrees, 0);
imagefilter($image, IMG_FILTER_MEAN_REMOVAL, 0);
imagefilter($image, IMG_FILTER_SMOOTH, 0);
//add some text
$text = 'Easter Egg by Troy Jordan 2008 using only php & gd';
//place font in same path as this script
putenv('GDFONTPATH=' . realpath('.'));
//change this font to the name of your font
$font = 'ACAKZIDE.TTF';
// Add some shadow to the text
imagettftext($image, 18, 0, 13, 21, $grey, $font, $text);
// Add the text
imagettftext($image, 18, 0, 12, 20, $white, $font, $text);
//resize the image
$width = imagesx($image);
$height = imagesy($image);
if($height > 0) { $ratio = $width/$height; }
$rand = rand(25,75);
$perc = $rand/100;
$newwidth = $width * $perc;
$newheight = $height * $perc;
$image2 = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($image2, $image, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
header("Content-type: image/png");
imagepng($image2);
?>
somebody learning php
12-Mar-2008 12:34
12-Mar-2008 12:34
This is regarding a note below titled "sampathperera at hotmail dot com - Sri Lanka". It is incomplete. A much better version is at (concat lines below to construct URL):
http://www.planet-source-code.com/vb/scripts/ShowCode.asp?
txtCodeId=739&lngWId=8
If the link is broken, google for Image Verification Tutorial by Darryl Porter.
ph_corp at yahoo dot fr
23-Dec-2007 07:19
23-Dec-2007 07: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 );
}
?>
kangaroo232002 at yahoo dot co dot uk
14-Nov-2007 07:51
14-Nov-2007 07:51
I have noticed that some functions use quite complicated resizing code, however if you want to specify just one dimension (e.g. resizing an image for a catalogue or social network etc) then you can do it my just getting the percentage reduction of one dimension of the image and applying it to the other, like so:
<?php
$new_width = 150;
//assuming you have already used imageSX(), imageSY() to get the dimensions.
$percentage_reduction = ($new_width / $old_width) * 100;
$new_height = ($old_height / 100) * $percentage_reduction;
?>
This means that images will not be stretched, but will be neater as they are the same width (e.g. facebook).
zilly at adminc dot org
20-Oct-2007 11:10
20-Oct-2007 11:10
Here is an Example of what can be done using GD and Php.
There is a whole 3D-Dungeon realized and rendered in Real-Time using GD:
http://www.quizzen.de/labyrinth/
joachim dt werner a diggin-data dt de
30-Aug-2007 02:44
30-Aug-2007 02:44
In reply to diggertadmin at gmail dot com:
I had the effect that my thumbnail script exceeded the memory limit, too.
However, as error_reporting was turned off, Firefox just printed out the script URL.
Internet Explorer was more helpful here.
maps at cwsol dot com
23-Apr-2007 03:28
23-Apr-2007 03:28
If you are getting the generic error "The image cannot be displayed, because it contains errors.", comment out header("Content-type: image/png");. This will enable PHP to display the real PHP errors.
felipe dot medeiros at kanashii dot com dot br
27-Mar-2007 01:41
27-Mar-2007 01:41
Jonathon Reinhart, don't assume it.
.SO and .A files are libraries for dynamic and stactic linking when you compile a program. just to install <package> isn't enought to compile against it's libraries, as them may be only run-time libraries and give you some headache. The correct is to install <package>-devel, which will give you the right libraries for compile time.
And one final word... linux is by now a stable system with lots of working done... if the thing you're trying to do is too hard or unexplained it means that either you're trying something noone ever cared about spending his time on it or you didn't readed how to do it properly. Either way try to learn more about what you're trying.
Jonathon dot Reinhart at DONTSPAMgmail dot com
13-Mar-2007 02:48
13-Mar-2007 02:48
I've seen a lot of issues with getting PHP compiled with jpeg and png support. I built it under SuSE 10.2 and ./configure kept giving me "libjpeg.(a|so) not found". I believe that's because my libjpeg was libjpeg.so.62. It also did this for libpng (which mine was named libpng12.so)
Apparently ./config is looking only for the .so files. To resolve this, I installed libjpeg-devel and libpng-devel, which then created symlinks: libpng.so -> libpng12.so and libjpeg.so -> libjpeg.so.62.0.0 . I'm assuming creating these symlinks without installing the -devel packages will work just fine.
snagnever at gmail dot com
03-Mar-2007 03:38
03-Mar-2007 03:38
A lot of GD effects in functions, like:
greyscale, sepia, filling, better-merging, fading
can be found here:
Examples Page:
http://beta.sn4g.net/gd.fillAndMerge.php
Source: http://url.sn4g.net/1u
They all work on PHP 4 and 5. Functions well documented, just copy and use it.
Others Proof of Concepts at http://beta.sn4g.net/
Skyeye
20-Aug-2006 06:04
20-Aug-2006 06:04
In addition to %0A which you can use for making multiline text images, you can also use underlining and strikethrough.
For underlining use %0D and _, for example:
/image.php?text=Underline.%0D________
For strikethrough use %0D and %E2%80%93, for example:
/image.php?text=Strikethrough.%0D%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
If you want to use both of them in one line you will have to use %20 to dispose the next block of modifying symbols:
/image.php?text=Underline%20and%20Strikethrough.%0D_______%20%20%20%20
%20%20%20%20%20%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93
As you see all modifying symbols for whole line are put after %0D in one string after the whole modifyable text and not after each modifyable word. This makes easy to put on and take off modifying string for whole line when it`s necessary.
If the text is on several lines, each line has its own disposition of modifying symbols:
/image.php?text=Underline%20and%0D_______%0AStrikethrough.%0D%E2%80%93
%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93%E2%80%93
%E2%80%93%E2%80%93
Theese are only some examples how to use symbol combining. Using %0D and other symbols from Windows Charmap you can easy make images of characters which even doesn`t exist in any font.
Skyeye
19-Aug-2006 07:43
19-Aug-2006 07:43
If you want to make an image through GET with text in several lines, use %0A for line separating, for example:
/image.php?text=Text%20string%0Ain%20several%0Alines.
As also you can make php generated images without other knowing that they are php-made. Simply add the image extension in Apache httpd.conf file:
AddType application/x-httpd-php .php .png
And call image as normal png image:
/somephpautogeneratedimage.png
Of course real .png files will be now treated as php, but if you don`t have png files on your webserver, this won`t be a problem. Or you can use this code for displaying real png images through php code:
<?php
$filename = 'realpngfile.png';
header('Content-type: image/png');
header('Content-length: '.filesize($filename));
readfile($filename);
?>
thomas at tgohome dot com
18-Aug-2006 07:01
18-Aug-2006 07:01
I wrote this script to fetch details about a GIF image. I wanted to use it for avatar details on a CMS system, so I wrote it to return an array of details (instead of having to go through all of the functions)
Without further ado, here the script is:
<?
/*
* Get GIF image data
* Returns an array of data, including GIF image type, and
* the width and height of the image, plus transparent colour
* details and much more.
*
* Copyright 2006 Thomas Oldbury.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/*
* This function takes one argument, $file, a direct link to the image in
* question. Perhaps in future versions it will get the file from an image
* resource, but for now, it will have to do.
*/
function fetch_gif_data($file) {
/*
* First, we need to get the contents of the file in question, or we print
* a warning using trigger_error().
*/
$file_data = @file_get_contents($file) or trigger_error("File $file does not exist", E_USER_WARNING);
/*
* Now we need to fetch the gif image's version. We'll use strpos to fetch
* gif89a, gif87a or if we don't get that then we will print an error.
*/
$image_type = strpos($file_data, "g");
/*
* Now we check to see wether it is actually a GIF image, as it may not be
* an image and if this is the case, problems could occur.
*/
if($image_type === false) {
trigger_error("File $file is not a gif89a or gif87a compatible image", E_USER_ERROR);
}
/*
* Now, we need to fetch the image type by fetching the text at a certain
* position, using PHP's function substr.
*/
$image_info[version] = substr($file_data, 0, 6);
$image_info[file_reg_version] = substr($file_data, 3, 3);
/*
* Let's get the total number of colours in this image using a special
* piece of code, which fetches all the image's colours.
*/
$im_gif = imagecreatefromgif($file);
$image_info[total_pallete_colours] = imagecolorstotal($im_gif);
/*
* Now, the next thing we need to do is get the width and height of the
* image in question by using imagesx(); and imagesy();
*/
$image_info[width] = imagesx($im_gif);
$image_info[height] = imagesy($im_gif);
/*
* Let's fetch the transparent color of the image, if there is one.
*/
$id = imagecolortransparent($im_gif);
$image_info[transparent_color_id] = $id;
$image_info[transparent_color_values] = imagecolorsforindex($im_gif, $id);
/*
* Now, we return all the data.
*/
return $image_info;
}
/*
* Usage Example:
*/
echo '<pre>';
print_r(fetch_gif_data("hello.gif"));
echo '</pre>';
?>
This script returns something like:
Array
(
[version] => GIF89a
[file_reg_version] => 89a
[total_pallete_colours] => 251
[width] => 100
[height] => 100
[transparent_color_id] => 16
[transparent_color_values] => Array
(
[red] => 0
[green] => 0
[blue] => 0
[alpha] => 127
)
)
Tested on PHP 5.1.2, but should work on older versions.
sampathperera at hotmail dot com - Sri Lanka
21-Jul-2006 01:04
21-Jul-2006 01:04
I have used following function to generate Security Images to authenticate users are real humans. Need to have GD graphic library with FreeType enabled.
Used a gif file as background, put random text on it & creates a new gif file as output.
<?php
function createImage(){
// creates the images, writes the file
$fileRand = md5(rand(100000,999999));
$string_a = array("A","B","C","D","E","F","G","H","J","K",
"L","M","N","P","R","S","T","U","V","W","X","Y","Z",
"2","3","4","5","6","7","8","9");
$keys = array_rand($string_a, 6);
foreach($keys as $n=>$v){
$string .= $string_a[$v];
}
$backgroundimage = "security_background.gif";
$im=imagecreatefromgif($backgroundimage);
$colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255));
$font = 'Arial';
$angle = rand(-5,5);
// Add the text
imagettftext($im, 16, $angle, 15, 25, $colour, $font, $string);
$outfile= "$fileRand.gif";
imagegif($im,$outfile);
return $outfile;
}
echo "<IMG SRC=".createImage()." name=secimg>";
?>
g8z at yahoo dot com
20-Jul-2006 04:39
20-Jul-2006 04:39
<?php
/**
chunk_image breaks an image into roughly equal chunks horizontally (which are returned in an array of image resources)
parameters:
$image = image resource to work on
$chunks = number of chunks to break the image into
Courtesy of the $5 Script Achive: http://www.tufat.com
**/
function chunk_image_horizontally ($image, $chunks = 1)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
// calculate required chunk size
$chunk_size = round($image_width / $chunks);
// do all but the last chunk
for ($current_chunk = 1; $current_chunk < $chunks; $current_chunk++) {
// create image resource to store chunk
$chunk_images[$current_chunk - 1] = imagecreate($chunk_size, $image_height);
// copy chunk to chunk images array
imagecopy($chunk_images[$current_chunk - 1], $image, 1, 1, $chunk_size * ($current_chunk - 1) + 1 , 1, $chunk_size, $image_height);
}
// get last chunk
$chunk_images[$chunks - 1] = imagecreate($chunk_size, $image_height);
imagecopy($chunk_images[$chunks - 1], $image, 1, 1, $chunk_size * ($chunks - 1) + 1 , 1, $image_width, $image_height);
// return array
return $chunk_images;
}
//Example:
// read in test.jpg, and break it into 4 chunks using our function
$in_image = imagecreatefromjpeg('./image.jpg');
$images = chunk_image_horizontally($in_image, 4);
$count = 0;
// save chunks to files
foreach ($images as $image) {
$count++;
imagejpeg($image, './test_chunk'.$count.'.jpg');
}
?>
g8z at yahoo dot com
20-Jul-2006 04:36
20-Jul-2006 04:36
<?php
/**
change_color replaces $old_color with $new_color. $threshold allows you to specify how far away from the specified color a pixel can be and still be considered a match. $old_color and $new_color must be decimal color values.
Courtesy of the $5 Script Achive: http://www.tufat.com
*/
function change_color($image, $old_color, $new_color, $threshold = 15)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
// iterate through x axis
for ($x = 0; $x < $image_width; $x++) {
// iterate through y axis
for ($y = 0; $y < $image_height; $y++) {
// look at current pixel
$pixel_color = imagecolorat($image, $x, $y);
if (($pixel_color <= $old_color + $threshold) && ($pixel_color >= $old_color - $threshold)) {
// replace with new color
imagesetpixel($image, $x, $y, $new_color);
}
}
}
}
// EXAMPLE:
// convert all red in the image to green
$image = imagecreatefromjpeg('./test.jpg');
$red_rbg = 16646146;
$green_rbg = 65341;
change_color($image, $red_rbg, $green_rbg, 15);
imagejpeg($image, './test_changed.jpg');
?>
php at synvb dot com
22-Apr-2006 11:19
22-Apr-2006 11:19
Here is a single-function to flip, based on the one below.
<?php
function flipImage($image, $vertical, $horizontal) {
$w = imagesx($image);
$h = imagesy($image);
if (!$vertical && !$horizontal) return $image;
$flipped = imagecreatetruecolor($w, $h);
if ($vertical) {
for ($y=0; $y<$h; $y++) {
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
}
}
if ($horizontal) {
if ($vertical) {
$image = $flipped;
$flipped = imagecreatetruecolor($w, $h);
}
for ($x=0; $x<$w; $x++) {
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
}
}
return $flipped;
}
?>
shd at earthling dot net
28-Mar-2006 08:44
28-Mar-2006 08: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
13-Mar-2006 01:17
13-Mar-2006 01: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 )
?>
andrew dot barlow at gmail dot com
01-Mar-2006 01:47
01-Mar-2006 01:47
To create a simple transparent gif with black text with any TrueType Font...
Simple put this script into a PHP file and call it with the usual IMG tag.
You can also specify the font size for the IMG tag too.
Change the $font to your own font and upload it to the same directory as this script.
<?php
// Set the content-type
header("Content-type: image/gif");
$fontsize = 18;
if(@$_GET['fontsize']) {
$fontsize = $_GET['fontsize'];
}
$font = 'yourcustomfont.ttf';
$text = @$_GET['text'];
// Create the image
$size = imagettfbbox($fontsize, 0, $font, $text);
$width = $size[2] + $size[0] + 8;
$height = abs($size[1]) + abs($size[7]);
$im = imagecreate($width, $height);
$colourBlack = imagecolorallocate($im, 255, 255, 255);
imagecolortransparent($im, $colourBlack);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Add the text
imagefttext($im, $fontsize, 0, 0, abs($size[5]), $black, $font, $text);
// Using imagepng() results in clearer text compared with
imagegif($im);
imagedestroy($im);
?>
relsqui at chiliahedron dot com
18-Feb-2006 03:14
18-Feb-2006 03:14
<?php
// This is a correction to the image-flipping function I posted previously.
// The bitwise ands (&) were incorrectly written as logical ands (&&).
// Needless to say, that breaks the function in obnoxious--if amusing--ways.
define("VERTICAL", 1);
define("HORIZONTAL", 2);
function imageflip($image, $mode) {
$w = imagesx($image);
$h = imagesy($image);
$flipped = imagecreate($w, $h);
if ($mode & VERTICAL) {
for ($y = 0; $y < $h; $y++) {
imagecopy($flipped, $image, 0, $y, 0, $h - $y - 1, $w, 1);
}
}
if ($mode & HORIZONTAL) {
for ($x = 0; $x < $w; $x++) {
imagecopy($flipped, $image, $x, 0, $w - $x - 1, 0, 1, $h);
}
}
return $flipped;
}
?>
relsqui at chiliahedron dot com
14-Feb-2006 07:22
14-Feb-2006 07:22
On the offchance someone else should need one, here's a function you can use to randomly "mix" two colors, resulting in a "child" color with components of both. You might use it to come up with ideas for a color scheme, for example; the image section seemed as good a place for it as any.
<?php
// $mom and $dad should be integers, quite possibly the output of hexdec().
// Similarly, the return value $child will be an integer suitable for feeding to dechex().
breed_colors($mom, $dad) {
do { $maskhex .= rand()&1 ? "f" : "0"; } while (strlen($maskhex) < 6);
$mask = hexdec($maskhex);
$inversemask = $mask ^ 16777215;
$child = ($mom & $mask) | ($dad & $inversemask);
return $child;
}
// For example:
breed_colors(hexdec("012345"), hexdec("6789ab"));
// Let's say the random mask was ff0f0f.
// The inverse mask is therefore 00f0f0.
// $mom & $mask == 010305.
// $dad & $inversemask == 0080a0.
// Those two |ed together make 0183a5, which combines the traits of the parents into one $child.
?>
jan at anh dot sk
15-Jan-2006 08:03
15-Jan-2006 08:03
When outputing an image from a script to a browser, use header("Content-Length: XYZ") together with Content-Type header. This avoids problems rendering-displaying the image with some browsers (f.i. MSIE) - fixes random image cutting of image bottom parts. Image from cache example:
<?php
$cache_file = "imagecache/{$ID}.img";
header("Content-Type: image/jpeg");
header("Content-Length: ".filesize($cache_file));
$cache = fopen($cache_file,"r");
fpassthru($cache);
fclose($cache);
exit;
?>
Problem observed @ Linux, Apache 2.0, PHP 4.3.10
matrixhasu at gmail dot com
14-Jan-2006 07:44
14-Jan-2006 07:44
Sorry,
a little bug found in the previous note: what was
<?php
for ($i=0; $i<count($Values); $i++){
$graphValues[$i] =
($Values[$i] - $min*(1-2*$graphspacing)) *
(($imgHeight*(1-$graphspacing))/($max-$min));
}
