PHP: Image Functions - Manual

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

search for in the

gd_info iis_stop_service

Last updated: Sat, 27 Jan 2007

view this page in

# LXIII. Image Functions

# Введение

PHP is not limited to creating just HTML output. It can also be used to create and manipulate image files in a variety of different image formats, including gif, png, jpg, wbmp, and xpm. Even more convenient, PHP can output image streams directly to a browser. You will need to compile PHP with the GD library of image functions for this to work. GD and PHP may also require other libraries, depending on which image formats you want to work with.

You can use the image functions in PHP to get the size of JPEG, GIF, PNG, SWF, TIFF and JPEG2000 images.

With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images. This way you can read meta data generated by digital cameras. The exif functions do not require the GD library.

> Замечание: Read the requirements section about how to expand image capabilities to read, write and modify images. To read meta data of pictures taken by digital cameras you need the above mentioned exif extension.

# Требования

If you have the GD library (available at http://www.boutell.com/gd/) you will also be able to create and manipulate images.

The format of images you are able to manipulate depend on the version of GD you install, and any other libraries GD might need to access those image formats. Versions of GD older than gd-1.6 support GIF format images, and do not support PNG, where versions greater than gd-1.6 and less than gd-2.0.28 support PNG, not GIF. GIF support was re-enabled in gd-2.0.28.

> Замечание: Since PHP 4.3 there is a bundled version of the GD lib. This bundled version has some additional features like alpha blending, and should be used in preference to the external library since its codebase is better maintained and more stable.

> Замечание: Support for GD 1.x has been removed as of PHP 6.0.0, which requires GD 2.0.33 or later.

You may wish to enhance GD to handle more image formats.

Таблица 1. Supported image formats

Image format | Library to download | Notes
--- | --- | ---
`gif` |  | Only supported in GD versions older than gd-1.6 and newer than gd-2.0.28. Read-only GIF support is available with PHP 4.3.0 and the bundled GD-library. Write support is available since PHP 4.3.9 and PHP 5.0.1.
`jpeg-6b` | ftp://ftp.uu.net/graphics/jpeg/ |
`png` | http://www.libpng.org/pub/png/libpng.html | Only supported in GD versions greater than gd-1.6.
`xpm` | ftp://metalab.unc.edu/pub/Linux/libs/X/!INDEX.html | It's likely you have this library already available, if your system has an installed X-Environment.

You may wish to enhance GD to deal with different fonts. The following font libraries are supported:

Таблица 2. Supported font libraries

Font library | Download | Notes
--- | --- | ---
`FreeType 1.x` | http://www.freetype.org/ | Support removed as of PHP 6.0.0
`FreeType 2` | http://www.freetype.org/ |
`T1lib` | ftp://sunsite.unc.edu/pub/Linux/libs/graphics/) | Support for Postscript Type 1 fonts.

# Установка

To enable GD-support configure PHP `--with-gd[=DIR]`, where DIR is the GD base install directory. To use the recommended bundled version of the GD library (which was first bundled in PHP 4.3.0), use the configure option `--with-gd`. GD library requires libpng and libjpeg to compile.

In Windows, you'll include the GD2 DLL `php_gd2.dll` as an extension in `php.ini`. The GD1 DLL `php_gd.dll` was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.

To disable GD support in PHP 3 add `--without-gd` to your configure line.

Enhance the capabilities of GD to handle more image formats by specifying the `--with-XXXX` configure switch to your PHP configure line.

Таблица 3. Supported image formats

Image Format | Configure Switch
--- | ---
`jpeg-6b` | To enable support for jpeg-6b add `--with-jpeg-dir=DIR`.
`png` | To enable support for png add `--with-png-dir=DIR`. Note, libpng requires the zlib library, therefore add `--with-zlib-dir[=DIR]` to your configure line.
`xpm` | To enable support for xpm add `--with-xpm-dir=DIR`. If configure is not able to find the required libraries, you may add the path to your X11 libraries.

> Замечание: When compiling PHP with libpng, you must use the same version that was linked with the GD library.

Enhance the capabilities of GD to deal with different fonts by specifying the `--with-XXXX` configure switch to your PHP configure line.

Таблица 4. Supported font libraries

Font library | Configure Switch
--- | ---
`FreeType 1.x` | To enable support for FreeType 1.x add `--with-ttf[=DIR]`.
`FreeType 2` | To enable support for FreeType 2 add `--with-freetype-dir=DIR`.
`T1lib` | To enable support for T1lib (Postscript Type 1 fonts) add `--with-t1lib[=DIR]`.
`Native TrueType string function` | To enable support for native TrueType string function add `--enable-gd-native-ttf`.

# Настройка во время выполнения

There are no image specific configurations but you may be interested in the exif extension directives.

# Типы ресурсов

Данное расширение не определяет никакие типы ресурсов.

# Предопределенные константы

Перечисленные ниже константы определены данным расширением и могут быть доступны только в том случае, если 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)

`PNG_NO_FILTER` (integer)

`PNG_FILTER_NONE` (integer)

`PNG_FILTER_SUB` (integer)

`PNG_FILTER_UP` (integer)

`PNG_FILTER_AVG` (integer)

`PNG_FILTER_PAETH` (integer)

`PNG_ALL_FILTERS` (integer)

# Примеры

Пример 1. PNG creation with PHP

`<?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);
?>`

This example would be called from a page with a tag like: <img src="button.php?text=text">. The above button.php script then takes this "text" string and overlays it on top of a base image which in this case is "images/button1.png" and outputs the resulting image. This is a very convenient way to avoid having to draw new button images every time you want to change the text of a button. With this method they are dynamically generated.
add a note User Contributed Notes
Image Functions
snagnever at gmail dot com
02-Mar-2007 11: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/`
Neal Delfeld
06-Jan-2007 11:08
`I have been having trouble using gd on PHP Version 5.2.0.
I had PHP installed correctly, the correct dll was in the
extension directory, and the extension directory was
listed correctly. I restarted IIS a dozen times, trying to
make sure I had everything listed correctly. It wasn't until
I switched over to the executable (cgi) version of PHP (in
IIS) that I got it to work. I was previously using the ISAPI
version of PHP through IIS.
If this is a problem for other users, they should delete the
dll application mapping, and add the application mapping
for the cgi version.
To delete the mapping to the .dll version of PHP:
1 open IIS
2 expand the "local computer" tree (or wherever the
websites are listed)
3 right click on "web sites" and select "properties"
4 click the "home directory" tab
5 click "configuration"
6 under the "mapping" tab, find the ".php" mapping. If the
mapping is a .dll file, then select it, and click the "delete"
button.
to add mapping to the cgi version:
1 in the area where you left off in the deleting, click the
"add" button.
2 browse to find the PHP executable "php-cgi.exe". Keep
in mind that if you have PHP is a sub-directory, you may
have to use 8.3 notation:
"C:\Program Files\php\php-cgi.exe"
should be:
"C:\Progra~1\php\php-cgi.exe"
or else it won't work on some versions of IIS.
3 check the box next to "check if file exists"
4 click ok to the rest of the dialogs
5 restart IIS
The installation of PHP is better detailed in this website:
http://www.thephpguy.com/tutorials
/installing_PHP5_mysql_and_iis_on_windows.php#4
later,
Neal.`
jason at tectonic dot co dot za
15-Nov-2006 03:26
`function chromagradient(&$image, $startgradient, $endgradient, $chromacolor) {
$testcolor=imagecolorallocate($image,30,50,10);
$width=imagesx($image);
$height=imagesy($image);
$endindex=imagecolorsforindex($image,$endgradient);
$startindex=imagecolorsforindex($image,$startgradient);
$reddiff=$startindex['red']-$endindex['red'];
$greendiff=$startindex['green']-$endindex['green'];
$bluediff=$startindex['blue']-$endindex['blue'];
$found=false;
$y=0;
while ((!$found) && ($y<$height)) {
$x=0;
while(($x<$width) && (!$found)) {
$col=imagecolorat($image,$x,$y);
if ($col==$chromacolor) {
$startpoint=$y;
$found=true;
break;
}
$x++;
}
$y++;
}
$found=false;
$y=$height;
while ((!$found) && ($y>0)) {
for ($x=0;$x<$width;$x++) {
$col=imagecolorat($image,$x,$y);
if ($col==$chromacolor) {
$endpoint=$y;
$found=true;
break;
}
}
$y--;
}
$gheight=$endpoint-$startpoint;
for ($x=0;$x<$width;$x++) {
for ($y=$startpoint;$y<$endpoint;$y++) {
$newblue=$startindex['blue'] - floor(($y-$startpoint)*$bluediff/($gheight));
$newgreen=$startindex['green'] - floor(($y-$startpoint)*$greendiff/($gheight));
$newred=$startindex['red'] - floor(($y-$startpoint)*$reddiff/($gheight));
$replacementcol=imagecolorallocate($image, $newred, $newgreen, $newblue);
$col=imagecolorat($image,$x,$y);
if ($col==$chromacolor) {
imagesetpixel($image,$x,$y,$replacementcol);
}
}
}
}`
Skyeye
19-Aug-2006 03: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
18-Aug-2006 04: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
17-Aug-2006 04: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.`
japidoff isliev nl
11-Aug-2006 03:12
`quite a hassle, but here it is:
gd "Sepia" effect, also called colorisation...
all the math (rgb<->hsl) comes from
http://www.easyrgb.com/math.php
it is NOT optimised, it takes about 10sec for a 500x400 jpeg @2ghz
<?
Function RGB_to_HSL($RGB){
$var_R = $RGB[0] / 255; //Where RGB values = 0 ÷ 255
$var_G = $RGB[1] / 255;
$var_B = $RGB[2] / 255;
$var_Min = min( $var_R, $var_G, $var_B ); //Min. value of RGB
$var_Max = max( $var_R, $var_G, $var_B ); //Max. value of RGB
$del_Max = $var_Max - $var_Min; //Delta RGB value
$L = ($var_Max + $var_Min) / 2;
if ($del_Max == 0){ //This is a gray, no chroma...
$H = 0; //HSL results = 0 ÷ 1
$S = 0;
}else{ //Chromatic data...
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;
}elseif ($var_G == $var_Max){
$H = (1 / 3) + $del_R - $del_B;
}elseif($var_B == $var_Max){
$H = (2 / 3) + $del_G - $del_R;
}
if ($H < 0){
$H++;
}
if($H > 1){
$H--;
}
}
Return array($H, $S, $L);
}
Function HSL_to_RGB($HSL){
$H = $HSL[0];
$S = $HSL[1];
$L = $HSL[2];
if ($S == 0){ //HSL values = 0 ÷ 1
$R = $L * 255; //RGB results = 0 ÷ 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 = Round(255 * Hue_2_RGB($var_1, $var_2, $H + (1/3)));
$G = Round(255 * Hue_2_RGB($var_1, $var_2, $H));
$B = Round(255 * Hue_2_RGB($var_1, $var_2, $H - (1/3)));
}
Return array($R, $G, $B);
}
Function Hue_2_RGB($v1, $v2, $vH){ //Function Hue_2_RGB
if ($vH < 0){
$vH++;
}
if ($vH > 1){
$vH--;
}
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 RGB_to_gray($RGB){
$val = round((0.299 * $RGB[0]) + (0.587 * $RGB[1]) + (0.114 * $RGB[2]));
Return array($val, $val, $val);
}
$old_image =imagecreatefromjpeg("./test.jpg");
$old_x = imagesx($old_image);
$old_y = imagesy($old_image);
$new_image = imagecreatetruecolor($old_x, $old_y);
for( $x = 0; $x < $old_x; $x++){
for( $y = 0; $y < $old_y; $y++){
$_rgb = ImageColorAt($old_image, $x, $y); //original color
$RGB[0] = ($_rgb >> 16) & 0xFF; //split 24 bit color in RGB values
$RGB[1] = ($_rgb >> 8) & 0xFF;
$RGB[2] = $_rgb & 0xFF;
$RGB = RGB_to_gray($RGB); //convert to grayscale
$HSL = RGB_to_HSL($RGB); //convert to HSL
$to_hsl = RGB_to_HSL(array(94,38,18)); //set "sepia" color
$HSL[0] = $to_hsl[0]; //change Hue and Saturation values from pixel
$HSL[1] = $to_hsl[1];
$RGB = HSL_to_RGB($HSL); //convert from HSL to RGB
$_rgb = intval(($RGB[2]) + ($RGB[1] << 8) + ($RGB[0] << 16)); //merge from RGB to 24 bit
imagesetpixel($new_image, $x, $y, $_rgb); //draw pixel in new image
}
}
header('Content-Control: cache');
header('Content-type: image/jpeg');
imagejpeg($new_image);`
sampathperera at hotmail dot com - Sri Lanka
20-Jul-2006 10: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
19-Jul-2006 01: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
19-Jul-2006 01: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
21-Apr-2006 08: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 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 )
?>`
andrew dot barlow at gmail dot com
28-Feb-2006 09: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
17-Feb-2006 11: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 03: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 04: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 03: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));
}
?>
now has to be
<?php
for ($i=0; $i<count($Values); $i++){
$graphValues[$i] =
($Values[$i] - $min*(1-2*$graphspacing)) *
(($imgHeight*(1-$graphspacing))/($max-$min*(1-2*$graphspacing)));
?>`
matrixhasu at gmail dot com
13-Jan-2006 04:02
`I've take the example of Peter Hulstaert and modified so:
1. grid width is scaled basing on the number of data points to print;
2. images are scaled by min and max values:
even if min is 1000, that point will be very close to the image bottom
Hope this will helpfull to someone.
<?
//Original from peter dot hulstaert at gmail dot com
//Available at http://it.php.net/manual/en/ref.image.php#60410
header("Content-type: image/png");
// Define variables
$Values=array(120,190,130,155,150,140,320,150,140,186,240,128,650);
$imgWidth=500;
$imgHeight=200;
$grid=25;
$graphspacing=0.07;
//Scales number of vertical grid lines for the number of data to print
$gridW=$imgWidth/(count($Values)-1);
//Get min and max values to scale image
for ($i=0; $i<count($Values); $i++){
if ($Values[$i]>$max){$max=$Values[$i];}
}
//Min values are less the maximum...
$min = $max;
for ($i=0; $i<count($Values); $i++){
if ($Values[$i]<$min){$min=$Values[$i];}
}
for ($i=0; $i<count($Values); $i++){
$graphValues[$i] =
($Values[$i] - $min*(1-2*$graphspacing)) *
(($imgHeight*(1-$graphspacing))/($max-$min));
}
// 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/$gridW); $i++)
{imageline($image, $i*$gridW, 0, $i*$gridW, $imgHeight, $colorGrey);}
for ($i=1; $i<($imgHeight/$grid); $i++)
{imageline($image, 0, $i*$grid, $imgWidth, $i*$grid, $colorGrey);}
//Create the lines connecting points
for ($i=0; $i<count($graphValues)-1; $i++)
{imageline($image, $i*$gridW, ($imgHeight-$graphValues[$i]),
($i+1)*$gridW, ($imgHeight-$graphValues[$i+1]), $colorBlue);}
// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>`
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);
?>`
razonklnbd at yahoo dot com
25-Dec-2005 11:12
`I was looking for a function to get propotional image size. After a bit of thinking I came up with this pretty fast solution:
<?php
function getPropotionalSize($src_w, $src_h, $max_w, $max_h){
$return_val['width']=$src_w;
$return_val['height']=$src_h;
if($max_w<$src_w || $max_h<$src_h){
$return_val['width']=$max_w;
$return_val['height']=$max_h;
if($src_w>=$src_h) $return_val['height']=($max_w*$src_h)/$src_w;
else $return_val['width']=($max_h*$src_w)/$src_h;
}
return $return_val;
}
?>
Hope it saved somebody some time!`
orbitphreak at yahoo dot com
06-Dec-2005 09:46
`If you want to have a dynamic image validation code
like yahoo, you can use this function:
<?php
function generateValidationImage($rand) {
global $site_font_path;
global $site_font_validation;
$width = 120;
$height = 40;
$image = imagecreate($width, $height);
$bgColor = imagecolorallocate ($image, 255, 255, 255);
$textColor = imagecolorallocate ($image, 0, 0, 0);
// Add Random noise
for ($i = 0; $i < 250; $i++) {
$rx1 = rand(0,$width);
$rx2 = rand(0,$width);
$ry1 = rand(0,$height);
$ry2 = rand(0,$height);
$rcVal = rand(0,255);
$rc1 = imagecolorallocate($image,
rand(0,255),
rand(0,255),
rand(100,255));
imageline ($image, $rx1, $ry1, $rx2, $ry2, $rc1);
}
// write the random number
$font = imageloadfont($site_font_path."/".$site_font_validation);
imagestring($image, $font, 3, 0, $rand, $textColor);
// send several headers to make sure the image is not cached
// Date in the past
header("Expires: Mon, 23 Jul 1993 05:00:00 GMT");
// always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
// send the content type header so the image is displayed properly
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
}
?>
The $site_font_path should be set to something like "/home/user/www/fonts".
The $site_font_validation should be set to the name of the GD font file,
like "anonymous.gdf".
You can view and download the code here:
http://www.digital-seven.net/?option=com_content&task=view&id=67`
Jonas Sweden
17-Nov-2005 03:51
`Simple script for getting a jpg-thumb by submitting imgname and either height or width of the thumb!
<?php
if(isset($_GET["i"]) && ("" != $_GET["i"])){
$fn = "path/to/jpgs/".$_GET["i"].".jpg";
if(false !== (list($ws,$hs) = @getimagesize($fn))){
if(isset($_GET["w"]) && ("" != $_GET["w"])){
$ratio = ((float)$_GET["w"]) / $ws;
}
elseif(isset($_GET["h"]) && ("" != $_GET["h"])){
$ratio = ((float)$_GET["h"]) / $hs;
}
if(isset($ratio)){
$wt = $ws * $ratio;
$ht = $hs * $ratio;
$thumb = imagecreatetruecolor($wt,$ht);
$source = imagecreatefromjpeg($fn);
imagecopyresampled($thumb,$source,0,0,0,0,$wt,$ht,$ws,$hs);
header('Content-type: image/jpeg');
imagejpeg($thumb);
imagedestroy($thumb);
}
}
}
?>`
skumar2k15 [at] gmail [dot] com
07-Nov-2005 02:24
`Generate a line graphs on-the-fly through php image functions.
<br>
code for linechart.php
<?
// Add values to the graph
$graphValues=array(0,80,23,11,190,245,50,80,111,240,55);
// Define .PNG image
header("Content-type: image/png");
$imgWidth=250;
$imgHeight=250;
// 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, 250, $colorGrey);
imageline($image, 0, 0, 250, 0, $colorGrey);
imageline($image, 249, 0, 249, 249, $colorGrey);
imageline($image, 0, 249, 249, 249, $colorGrey);
// Create grid
for ($i=1; $i<11; $i++){
imageline($image, $i*25, 0, $i*25, 250, $colorGrey);
imageline($image, 0, $i*25, 250, $i*25, $colorGrey);
}
// Create line graph
for ($i=0; $i<10; $i++){
imageline($image, $i*25, (250-$graphValues[$i]), ($i+1)*25, (250-$graphValues[$i+1]), $colorBlue);
}
// Output graph and clear image from memory
imagepng($image);
imagedestroy($image);
?>
Thanks and regards,
skumar k.`
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".`
trucex at gmail
27-Aug-2005 04:18
`@snagnever|gmail|com:
I modified the ascii image script you wrote so that it displays an image that looks real. While impractical due to speed, the concept is actually really cool. Here it is:
<?php
//
// image2asci - test script 2
// by sn4g <snagnever@gmail.com>
// 2005 - april - 2
// simple script that read "each" pixel from a image and
// outputs an html colorized version of it.
//
$name = basename($_GET['name']);
$file = "/path/to/images/" . $name;
if( file_exists($file) ) {
$what = getimagesize($file);
switch( $what['mime'] ){
case 'image/png' : $src_id = imagecreatefrompng($file); break;
case 'image/jpeg': $src_id = imagecreatefromjpeg($file); break;
case 'image/gif' : $old_id = imagecreatefromgif($file); $src_id = imagecreatetruecolor($what[0],$what[1]); imagecopy($src_id,$old_id,0,0,0,0,$what[0],$what[1]); break;
default: break;
}
}
else die("No such file");
if( $src_id ){
$x_size = imagesx($src_id);
$y_size = imagesy($src_id);
// if it really read each pixel, it'd be too slow and heavy. so, we only use every third pixel. This resizes the image (by 1/3 obviously), so set it to 1 if you don't want that.
$x_jump = $y_jump = 3;
// char/strings that will construct the image. it's randomly selected after,
// in the loop. a value in the array will be one pixel in the asci-image.
$pixel_char = array(0);
echo "The image is $x_size x $y_size\n";
echo "<span style='font-size:8px; font-weight:bold;'><style>td.a { width:1px; height:1px; }</style>";
echo "<table margin=0 cellspacing=0 cellpadding=0><tr>";
// now it has a 'nested loop' to read 'each' pixel and print it
for( $y = 0; $y < $y_size; $y+=$y_jump ){
for( $x = 0; $x < $x_size; $x+=$x_jump ){
if( $x >= $x_size || $y >= $y_size ) break;
$rgb = @imagecolorat($src_id, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if( $x >= $x_size ) break;
if( $y >= $y_size ) break;
$pc = rand(0,count($pixel_char)-1);
$pc = $pixel_char[$pc];
echo "<td class=a style='background-color:rgb($r,$g,$b)'></td>";
} // end of 'x' loop
echo "</tr><tr>\r\n"; // end of a line
} // end of 'y' loop
}
?>`
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`
tfl at netcabo dot pt
18-Aug-2005 03:48
`IE doesn't show TIFF files and standard PHP distribution doesn't support converting to/from TIFF.
ImageMagick (http://www.imagemagick.org/script/index.php) is a free software that can read, convert and write images in a large variety of formats. For Windows users it includes a PHP extension php_magickwand_st.dll (and yes, it runs under PHP 5.0.4).
When converting from TIFF to JPEG, you must also convert from CMYK color space to RGB color space as IE can't show CMYK JPGs either. Please note:
-TIFF files may have RGB or CMYK color space
-JPEG files may have RGB or CMYK color space
Here are example functions using ImageMagick extension:
- convert TIFF to JPEG file formats
- convert CMIK to RGB color space
- set image resolution to 300 DPIs (doesn't change image size in pixels)
<?php
function cmyk2rgb($file) {
$mgck_wnd = NewMagickWand();
MagickReadImage($mgck_wnd, $file);
$img_colspc = MagickGetImageColorspace($mgck_wnd);
if ($img_colspc == MW_CMYKColorspace) {
echo "$file was in CMYK format<br />";
MagickSetImageColorspace($mgck_wnd, MW_RGBColorspace);
}
MagickWriteImage($mgck_wnd, str_replace('.', '-rgb.', $file));
}
function tiff2jpg($file) {
$mgck_wnd = NewMagickWand();
MagickReadImage($mgck_wnd, $file);
$img_colspc = MagickGetImageColorspace($mgck_wnd);
if ($img_colspc == MW_CMYKColorspace) {
echo "$file was in CMYK format<br />";
MagickSetImageColorspace($mgck_wnd, MW_RGBColorspace);
}
MagickSetImageFormat($mgck_wnd, 'JPG' );
MagickWriteImage($mgck_wnd, str_replace('.tif', '.jpg', $file));
}
function to300dpi($file) {
$mgck_wnd = NewMagickWand();
MagickReadImage($mgck_wnd, $file);
$img_units = MagickGetImageUnits($mgck_wnd);
switch ($img_units) {
case MW_UndefinedResolution: $units= 'undefined'; break;
case MW_PixelsPerInchResolution: $units= 'PPI'; break;
case MW_PixelsPerCentimeterResolution: $units= 'PPcm'; break;
}
list($x_res, $y_res) = MagickGetImageResolution($mgck_wnd);
echo "$file<br /> x_res=$x_res $units - y_res=$y_res $units<br />";
if($x_res == 300 && $y_res == 300 && $img_units == MW_PixelsPerInchResolution) {return; }
MagickSetImageResolution($mgck_wnd, 300 , 300);
MagickSetImageUnits($mgck_wnd, MW_PixelsPerInchResolution);
MagickWriteImage($mgck_wnd, str_replace('.', '-300.', $file));
}
$file='photos/test-cmyk.tif';
//this is a TIFF file in CMYK format with a 96 DPI resolution
cmyk2rgb($file);
$file = str_replace('.', '-rgb.', $file);
to300dpi($file);
$file = str_replace('.', '-300.', $file);
tiff2jpg($file);
$file = str_replace('.tif', '.jpg', $file);
to300dpi($file);
/* no file name changes as ImageMagick reports 300 DPIs
$file = str_replace('.', '-300.', $file);
*/
list($width, $height, $type, $attr) = getimagesize($file);
$width = $width/3;
$height = $height/3;
echo "<img src=\"http://localhost/$file\" width=\"$width\" height=\"$height\" alt=\"getimagesize() example\" />";
echo "<br />$file => width=$width - height=$height - type=$type - attr=$attr<br /><br />";
$file='photos/test-rgb.tif';
//this is a TIFF file in RGB format with a 96 DPI resolution
cmyk2rgb($file);
$file = str_replace('.', '-rgb.', $file);
to300dpi($file);
$file = str_replace('.', '-300.', $file);
tiff2jpg($file);
$file = str_replace('.tif', '.jpg', $file);
to300dpi($file);
/* no file name changes as ImageMagick reports 300 DPIs
$file = str_replace('.', '-300.', $file);
*/
list($width, $height, $type, $attr) = getimagesize($file);
$width = $width/3;
$height = $height/3;
echo "<img src=\"http://localhost/$file\" width=\"$width\" height=\"$height\" alt=\"getimagesize() example\" />";
echo "<br />$file => width=$width - height=$height - type=$type - attr=$attr<br /><br />";
?>
Note - Although ImageMagick correctly sets JPEG files resolution to 300 DPIs, some programs might not notice it.`
Mark Rosenthal <mbr at arlsoft dot com>
14-Aug-2005 11:48
`In AmX's example of how to generate headers to prevent the browser
from trying to cache a script-generated image, he wrote: "I did not
yet find a way to get the filesize of a GD made image, so I assume you
save it to disk, get the filesize and read it again."
That's not necessary. Here's AmX's example, reworked to output the
correct "Content-Length: " header without the intermediate step of
storing the image in a file:
// The following code assumes that $gd has been set to the GD
// resource of the image we want to output.
// Turn on output buffering
ob_start();
// Output will now go to a buffer rather than the browser.
imagejpeg($gd);
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-type: image/jpeg");
// Tell the browser the number of bytes that have been
// written to the buffer.
header("Content-Length: " . ob_get_length());
// Now send the buffer's contents to the browser and turn off
// output buffering.
ob_end_flush();
// Remember to free the memory used by the GD resource, or the
// sever will eventually crash.
imagedestroy($gd);
// Headers and image data have been sent. We're done.
exit;`
Maarten Balliauw
03-Aug-2005 07:45
`A PHP "skew" function:
<?
$angle = 15;
$pDirection = 1;
header("Content-Type: image/png");
imagepng(ImageSkew("test.png", $angle, 1));
exit();
function ImageSkew($pImage, $pAngle, $pDirection = 0) {
// Source image
$iSource = ImageCreateFromPng("test.png");
// Destination image
list($width, $height, $type, $attr) = getimagesize($pImage);
$iCanvas = @imagecreate($width, $height);
$cCyan = imagecolorallocate($iCanvas, 255, 0, 255);
imagefill($iCanvas, 0, 0, $cCyan);
// Pixel differences
$diff = ($pAngle / 90);
// Loop trough each width pixel
$currentHeight = $height;
$currentY = 0;
if ($pDirection == 1) {
$currentHeight = 0;
$currentY = $height;
}
for ($i = 0; $i < $width; $i++) {
// Take 1*height sample and copy to iCanvas
if ($pDirection == 0) {
imagecopyresampled($iCanvas, $iSource, $i, $currentY, $i, 0, 1, $currentHeight, 1, $height);
} else {
imagecopyresampled($iCanvas, $iSource, ($width - $i), $currentY, ($width - $i), 0, 1, $currentHeight, 1, $height);
}
// Change heights
if ($pDirection == 0) {
$currentHeight = $currentHeight - ($diff * 2);
$currentY = ($height - $currentHeight) / 2;
} else {
$currentHeight = $height - ( $i * ($diff * 2) );
$currentY = ($height - $currentHeight) / 2;
}
}
// Return
return $iCanvas;
}
?>`
yasin yyalcinkaya at ku dot edu dot tr
29-Jul-2005 07:01
`firstly , i wrote this class. we can easily call it from anywhere. Soppose , its name is "imageuploader.class.php" and our main file's name is upload.php.
<?php
class Imenu
{
function Ifonc() {
echo "<table class=\"adminform\">"
."<form method=\"post\" action=\"upload.php\" enctype=\"multipart/form-data\" name=\"filename\">"
."<tr><th class=\"title\"> File Upload : $directory </th>"
."</tr><tr><td align=\"center\"><input class=\"inputbox\" name=\"userfile\" type=\"file\" />"
."</td></tr><tr><td>"
."<input class=\"button\" type=\"submit\" value=\"Upload\" name=\"fileupload\" />"
."</td><tr><td>"
."<input type=\"hidden\" name=\"directory\" value=\"$directory\" />"
."</td></tr></form>"
."</table>";
return true;
}
}
?>
then we use this part in our main function.
<?php
....
....
....
$userfile2=(isset($_FILES['userfile']['tmp_name']) ? $_FILES['userfile']['tmp_name'] : "");
$userfile_name=(isset($_FILES['userfile']['name']) ? $_FILES['userfile']['name'] : "");
if (isset($_FILES['userfile'])) {
if ($directory!="banners") {
$base_Dir = "images/";
} else {
$base_Dir = "images/";
}
if (empty($userfile_name)) {
echo "<script>alert('Please select an image to upload'); document.location.href='upload.php';</script>";
}
$filename = split("\.", $userfile_name);
if (eregi("[^0-9a-zA-Z_]", $filename[0])) {
echo "<script> alert('File must only contain alphanumeric characters and no spaces please.');</script>\n";
}
if (file_exists($base_Dir.$userfile_name)) {
echo "<script> alert('Image $userfile_name already exists.');</script>\n";
}
if ((strcasecmp(substr($userfile_name,-4),".gif")) && (strcasecmp(substr($userfile_name,-4),".jpg"))
&& (strcasecmp(substr($userfile_name,-4),".png")) && (strcasecmp(substr($userfile_name,-4),".bmp"))
&& (strcasecmp(substr($userfile_name,-4),".doc")) && (strcasecmp(substr($userfile_name,-4),".xls"))
&& (strcasecmp(substr($userfile_name,-4),".ppt")) && (strcasecmp(substr($userfile_name,-4),".swf"))
&& (strcasecmp(substr($userfile_name,-4),".pdf"))) {
echo "<script>alert('The file must be gif, png, jpg, bmp, swf, doc, xls or ppt');</script>\n";
}
if (eregi(".pdf", $userfile_name) || eregi(".doc", $userfile_name) || eregi(".xls", $userfile_name)
|| eregi(".ppt", $userfile_name)) {
if (!move_uploaded_file ($_FILES['userfile']['tmp_name']
,$media_path.$_FILES['userfile']['name'])
|| !chmod($media_path.$_FILES['userfile']['name'],0777)) {
echo "<script>alert('Upload of $userfile_name failed');</script>\n";
}
else {
echo "<script>alert('Upload of $userfile_name to $media_path successful');</script>\n";
}
} elseif (!move_uploaded_file ($_FILES['userfile']['tmp_name']
,$base_Dir.$_FILES['userfile']['name'])
|| !chmod($base_Dir.$_FILES['userfile']['name'],0777)) {
echo "<script>alert('Upload of $userfile_name failed'); </script>\n";
}
else {
echo "<script>alert('Upload of $userfile_name to $base_Dir successful'); </script>\n";
}
}
include_once "imageuploader.class.php";
$Imenu = new Imenu;
$Imenu ->Ifonc();
....
....
....
?>
with script we can upload our files.`
AmX
04-Jul-2005 03:03
`As many people found any PhP made image working standalone but not in an img tag, I 'll explain how I solved it.
//Part1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
//Part2
header('Content-Length: '.filesize($pic));
header('Content-type: image/jpeg');
readfile($pic);
Just some header work, the first part makes the image non-cacheable and the second one ensures the browser gets all the needed information.
As I did not need it I did not yet find a way to get the filesize of a GD made image, so I assume you save it to disk, get the filesize and read it again.
I hope I just helped you out, and saved you from 2 hours of finding out why the stupid PhP has to add data at the beginning of your image. It may look trivial, the Content-Length is not given by default!
AmX`
http://mike.eire.ca
30-Jun-2005 12:13
`ceo at l-i-e dot com:
II AND MM are referring to Intel and Motorola byte order within the TIFF image. If, for example, you save a TIFF in Photoshop you are given the option of 'PC' or 'Macintosh': this determines what byte order will be used to store the image. If you don't already know about byte order, you probably don't want to!`
alex at bestgames dot ro
30-Jun-2005 10:04
`This function helps you to create a simple statistic graphics.
Arguments
$values, values should be separed by comma
$options may be separed by comma options can be timeline=format, title=a string or image=a source, where format can be sec, min, hour, days/number, days/name, months/number, months/name or years.
$x, $y reffers to upper left corner where the graphic should begin
$image is the image resource
$graphic_color, $highlight_color, $grid_color are colors strings
Hope it will be useful!
Example of function:
function image_create_grid("1,2,3,4,5", "title=A simple graphic,timeline=months/name", 0, 0, $image, "navy, "green", "gray")
The source can be accessed at http://www.bestgames.ro/source/statistics.txt, it was too long to bve posted here.`
marc dot van dot nuffel at dudagroup dot com
04-Jun-2005 05:11
`Beauty of an example for the gd libary !
http://www.nyphp.org/content/presentations/GDintro
greez
_nu`
Adalius
04-Jun-2005 01:48
`After being driven batty for a good day and a half at why *any* of the image output functions were giving me the infamous 'The image �<path>� cannot be displayed, because it contains errors.' message with *no* php error in the source, make sure if you have an auto pre/append script it doesn't have any extra blank lines at the start or the end as they'll cause this problem when the browser tries to view the buffer as an image file.`
ceo at l-i-e dot com
19-May-2005 09:50
`IMAGETYPE_TIFF_II
IMAGETYPE_TIFF_MM
This may be patently obvious to experts, and I'm sure somehwere in the GD documentation it's spelled out, but...
It would be Really Nifty to have some explanation of the subtle difference between these two documented here...`
Michiel van de Vis
11-May-2005 11:08
`After testing this more carefully, i noticed a bug.
This can be resolved by replacing the getDeltaArray function by this one:
<?php
function getDeltaArray($col1, $col2, $size)
{
$r_range = $col1[0] - $col2[0];
$g_range = $col1[1] - $col2[1];
$b_range = $col1[2] - $col2[2];
$delta_r = $r_range/$size;
$delta_g = $g_range/$size;
$delta_b = $b_range/$size;
return array($delta_r, $delta_g, $delta_b);
}
?>
Hope this can be of help for anyone.`
Michiel van de Vis
11-May-2005 09:48
`Inspirated by several functions below, i wrote a function to create a gradient like in a color picker.
----------------------------------
| COL 1 COL2|
| |
| |
| |
| |
| COL 3 COL4|
----------------------------------
That is, 4 color which "gradient" to the center of the image.
Not 100% tested, but i believe most errors are gone.
<?php
function imagegradient($x_size,
$y_size,
$left_upper="FFFFFF", $right_upper="FF0000",
$left_lower="000000", $right_lower="000000")
{
$image = imagecreatetruecolor($x_size,$y_size);
$right_upper = getColorArray($right_upper);
$left_upper = getColorArray($left_upper);
$left_lower = getColorArray($left_lower);
$right_lower = getColorArray($right_lower);
if(($x_size*$y_size)<=10000)
$size = 1;
else
$size = 5;
$left = $left_upper;
$right = $left_lower;
list($r, $g, $b) = $left;
$delta_x1 = getDeltaArray($left, $right_upper, $x_size);
$delta_x2 = getDeltaArray($right, $right_lower, $x_size);
for($i=0;$i<$x_size;$i+=$size)
{
list($r, $g, $b) = $left;
for($j=0;$j<$y_size;$j+=$size)
{
$delta_y = getDeltaArray($left, $right, $y_size);
$r = $r - ($delta_y[0]*$size);
$g = $g - ($delta_y[1]*$size);
$b = $b - ($delta_y[2]*$size);
$col = imagecolorallocate($image, round($r), round($g), round($b));
imagefilledrectangle($image, $i, $j, $i+$size, $j+$size, $col);
}
$left[0] = $left[0] - ($delta_x1[0]*$size);
$left[1] = $left[1] - ($delta_x1[1]*$size);
$left[2] = $left[2] - ($delta_x1[2]*$size);
$right[0] = $right[0] - ($delta_x2[0]*$size);
$right[1] = $right[1] - ($delta_x2[1]*$size);
$right[2] = $right[2] - ($delta_x2[2]*$size);
}
return $image;
}
function getDeltaArray($col1, $col2, $size)
{
$r_range = $col1[0] - $col2[0];
$g_range = $col1[1] - $col2[1];
$b_range = $col1[2] - $col2[2];
if($r_range<0) $r_range*=-1;
if($g_range<0) $g_range*=-1;
if($b_range<0) $b_range*=-1;
$delta_r = $r_range/$size;
$delta_g = $g_range/$size;
$delta_b = $b_range/$size;
return array($delta_r, $delta_g, $delta_b);
}
function getColorArray($col)
{
list($r, $g, $b) = sscanf($col, "%2x%2x%2x");
return array($r, $g, $b);
}
?>`
j at jgdataworks dot com
05-May-2005 07:33
`Here is a class that I wrote, it supports scaling images on the fly:
scale to desired dimensions
scale to maximum
scale to ratio (relative to 1.0)
it could be easily modified for other features as well.
It can be included in your scripts, or called directly like this: <img src="image.php?img=/imgs/logo.png;sm,200">
Check it out:
http://jgdataworks.com/OSS/Image.class.phps
If you like it, drop me a note. Thanks.`
info at b1g dot de
24-Apr-2005 09:35
`Sorry, my function had got a little bug. Here is the corrected one.
<?php
function Graph($data, $w, $h, $titel, $y_titel, $x_titel, $y_start_with_null=true, $x_start_with_null=true)
{
$typ_farben = array('0000FF', 'FF0000', '006600', 'FF9900', '663300');
// Maximal- und Minimalwerte ermitteln
$min_x = 0xFFFFFFFF;
$max_x = 0x00000000;
$min_y = 0xFFFFFFFF;
$max_y = 0x00000000;
foreach($data as $typ)
{
foreach($typ['data'] as $x => $y)
{
$min_x = min($min_x, $x);
$max_x = max($max_x, $x);
$min_y = min($min_y, $y);
$max_y = max($max_y, $y);
}
}
reset($data);
if($y_start_with_null)
$min_y = 0;
if($x_start_with_null)
$min_x = 0;
// Bild erstellen
$im = imagecreate($w, $h);
// Basisfarben registrieren
$grey = imagecolorallocate($im, 240, 240, 240);
$black = imagecolorallocate($im, 0, 0, 0);
// Den Typen Farben zuordnen und im Bild registrieren
$i = 0;
foreach($data as $key=>$typ)
{
if($i > (count($typ_farben)-1))
$i = 0;
$data[$key]['color'] = imagecolorallocate($im, hexdec(substr($typ_farben[$i], 0, 2)), hexdec(substr($typ_farben[$i], 2, 2)), hexdec(substr($typ_farben[$i], 4, 2)));
$i++;
}
reset($data);
// Grungeruest zeichnen
imagestring($im, 2, (($w/2) - ((strlen($titel)*6)/2)), 8, $titel, $black);
imagestring($im, 2, 60, 28, $y_titel, $black);
imagestring($im, 2, $w-30-(strlen($x_titel)*6), $h-28, $x_titel, $black);
imageline($im, 40, 30, 40, $h-60, $black);
imageline($im, 40, $h-60, $w-30, $h-60, $black);
$graph_width = $w-30-40;
$graph_height = $h-40-60;
$x_segment = @($graph_width / ($max_x - $min_x));
$y_segment = @($graph_height / ($max_y - $min_y));
// Raster Y-Achse
$raster_y = ($max_y > (floor($graph_height/22)) ? floor($graph_height/22) : $max_y);
for($i=$min_y; $i<=$raster_y; $i++)
{
$y = ($h-60) - (($i-$min_y)*@($graph_height/($raster_y-$min_y)));
$zahl = round(($i-$min_y)*@($max_y/($raster_y-$min_y)), 0)+$min_y;
imageline($im, 36, $y, 40, $y, $black);
imagestring($im, 2, $max_y < 10 ? 15 : 10, $y-6, $zahl, $black);
}
// Raster X-Achse
$raster_x = ($max_x > floor($graph_width/32)) ? floor($graph_width/32) : $max_x;
for($i=$min_x; $i<=$raster_x; $i++)
{
$x = 40 + (($i-$min_x)*($graph_width/($raster_x-$min_x)));
$zahl = round(($i-$min_x)*($max_x/($raster_x-$min_x)), 0)+$min_x;
imageline($im, $x, $h-60, $x, $h-54, $black);
imagestring($im, 2, $max_x < 10 ? $x-3 : $x-5, $h-45, $zahl, $black);
}
// Daten zeichnen
$last_legend_x = 10;
foreach($data as $typ)
{
// Legende zeichnen
imagefilledrectangle($im, $last_legend_x, $h-25, $last_legend_x+6, $h-18, $typ['color']);
imagerectangle($im, $last_legend_x, $h-25, $last_legend_x+6, $h-18, $black);
$last_legend_x += 10;
imagestring($im, 2, $last_legend_x, $h-28, $typ['titel'], $typ['color']);
$last_legend_x += (strlen($typ['titel']) * 6) + 10;
// Graph zeichnen
$last_x = 0;
$last_y = 0;
foreach($typ['data'] as $x=>$y)
{
$new_x = 40+(($x-$min_x)*$x_segment);
$new_y = ($h-60)-(($y-$min_y)*$y_segment);
imageline($im, $last_x==0 ? $new_x : $last_x, $last_y==0 ? $new_y : $last_y, $new_x, $new_y, $typ['color']);
imagefilledrectangle($im, $new_x-1, $new_y-1, $new_x+1, $new_y+1, $typ['color']);
$last_x = $new_x;
$last_y = $new_y;
}
}
// Bild ausgeben
header('Content-Type: image/png');
imagepng($im);
}
?>`
snagnever at gmail dot com
02-Apr-2005 09:27
`Here i'm again... i have made little improvements on the last post, so i'll post the new one here. The same that the old one image to "asci"
<?php
//
// image2asci - test script 2
// by sn4g <snagnever@gmail.com>
// 2005 - april - 2
// simple script that read "each" pixel from a image and
// outputs an html colorized version of it.
//
$name = basename($_GET['name']);
$file = "/path/to/images/" . $name;
if( file_exists($file) ) {
$what = getimagesize($file);
switch( $what['mime'] ){
case 'image/png' : $src_id = imagecreatefrompng($file); break;
case 'image/jpeg': $src_id = imagecreatefromjpeg($file); break;
case 'image/gif' : $old_id = imagecreatefromgif($file); $src_id = imagecreatetruecolor($what[0],$what[1]); imagecopy($src_id,$old_id,0,0,0,0,$what[0],$what[1]); break;
default: break;
}
}
else die("No such file");
if( $src_id ){
$x_size = imagesx($src_id);
$y_size = imagesy($src_id);
// if it really read each pixel, it'd be too slow and heavy. so, here we determine
// how many pixels the script must 'jump' each loop. tip: y jump must be greater
// than the x jump, to decrease the distorcion.
$x_jump = 2;
$y_jump = 3;
// char/strings that will construct the image. it's randomly selected after,
// in the loop. a value in the array will be one pixel in the asci-image.
$pixel_char = array(0);
echo "The image is $x_size x $y_size\n";
echo "<span style='font-size:8px; font-weight:bold;'>";
echo "<pre>";
// now it has a 'nested loop' to read 'each' pixel and print it
for( $y = 0; $y < $y_size; $y+=$y_jump ){
for( $x = 0; $x < $x_size; $x+=$x_jump ){
if( $x >= $x_size || $y >= $y_size ) break;
$rgb = @imagecolorat($src_id, $x, $y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if( $x >= $x_size ) break;
if( $y >= $y_size ) break;
$pc = rand(0,count($pixel_char)-1);
$pc = $pixel_char[$pc];
echo "<font style='color:rgb($r,$g,$b)'>$pc</font>";
} // end of 'x' loop
echo "\r\n"; // end of a line
} // end of 'y' loop
}
?>`
jasperbg at gmail dot com
26-Mar-2005 09:14
`To those writing a new function to create a generic imagecreatefromfile() function: You are making it needlessly complex. Why not just:
<?php
$image = imagecreatefromstring(file_get_contents("/path/to/image.ext"));
?>`
2064*nojunk* at earthlink dot net
17-Mar-2005 07:15
`.::SHARPEN YOUR IMAGES::.
---by Alex R. Austin
I became aware that there is just NO image sharpening in PHP4. Thus, writing code for my photo album I found that using resize function "imagecopyresampled" would blur my thumbnails. After not finding any way to sharpen my thumbs I wrote this code. Please keep in mind that PHP is not C++ and speed is somewhat slow. I have optimised my code as far as I could. If you can make it faster be my guest. The 800x600 image gets sharpened on my machine in 9 seconds. A 200x150 thumbnail takes only half a second. Thus, it is not that bad.
<?
$filename='test.jpg';
list($width, $height) = getimagesize($filename);
$img = imagecreatefromjpeg($filename);
$pix=array();
//get all color values off the image
for($hc=0; $hc<$height; ++$hc){
for($wc=0; $wc<$width; ++$wc){
$rgb = ImageColorAt($img, $wc, $hc);
$pix[$hc][$wc][0]= $rgb >> 16;
$pix[$hc][$wc][1]= $rgb >> 8 & 255;
$pix[$hc][$wc][2]= $rgb & 255;
}
}
//sharpen with upper and left pixels
$height--; $width--;
for($hc=1; $hc<$height; ++$hc){
$r5=$pix[$hc][0][0];
$g5=$pix[$hc][0][1];
$b5=$pix[$hc][0][2];
$hcc=$hc-1;
for($wc=1; $wc<$width; ++$wc){
$r=-($pix[$hcc][$wc][0]);
$g=-($pix[$hcc][$wc][1]);
$b=-($pix[$hcc][$wc][2]);
$r-=$r5+$r5; $g-=$g5+$g5; $b-=$b5+$b5;
$r5=$pix[$hc][$wc][0];
$g5=$pix[$hc][$wc][1];
$b5=$pix[$hc][$wc][2];
$r+=$r5*5; $g+=$g5*5; $b+=$b5*5;
$r*=.5; $g*=.5; $b*=.5;
//here the value of 0.75 is like 75% of sharpening effect
//Change if you need it to 0.01 to 1.00 or so
//Zero would be NO effect
//1.00 would be somewhat grainy
$r=(($r-$r5)*.75)+$r5;
$g=(($g-$g5)*.75)+$g5;
$b=(($b-$b5)*.75)+$b5;
if ($r<0) $r=0; elseif ($r>255) $r=255;
if ($g<0) $g=0; elseif ($g>255) $g=255;
if ($b<0) $b=0; elseif ($b>255) $b=255;
imagesetpixel($img,$wc,$hc,($r << 16)|($g << 8)|$b);
}
}
//save pic
imageinterlace($img,1);
imagejpeg($img,'test_save.jpg',99);
imagedestroy($img);
?>`
ozeryumsek
14-Mar-2005 01:33
`3 level questionary image:
It shows each 3 level graph
<?php
function drawRating($rating1,$rating2,$rating3) {
//Creating image area //
$image = imagecreate(550,100);
//Describing Colors//
$back = ImageColorAllocate($image,255,255,255);
$border = ImageColorAllocate($image,0,0,0);
$fill = ImageColorAllocate($image,44,81,150);
//Creating Backside //
ImageFilledRectangle($image,0,0,302,20,$back);
ImageFilledRectangle($image,0,30,302,50,$back);
ImageFilledRectangle($image,0,60,302,80,$back);
//Creating Filled Side //
ImageFilledRectangle($image,1,1,$rating1,19,$fill);
ImageFilledRectangle($image,1,31,$rating2,49,$fill);
ImageFilledRectangle($image,1,61,$rating3,79,$fill);
//Creating Borders//
ImageRectangle($image,0,0,300,20,$border);
ImageRectangle($image,0,30,300,50,$border);
ImageRectangle($image,0,60,300,80,$border);
//Texts //
ImageString($image,5 , 310, 0 ,"Yetersiz Buldum - %$rateyuz1",$border);
ImageString($image,5 , 310, 30,"Daha Iyi Olabilir - %$rateyuz2", $border);
ImageString($image,5 , 310, 60,"Begendim - %$rateyuz3", $border);
//Picturing//
imagePNG($image);
//Deleting from Memory//
imagedestroy($image);
}
drawRating (48,26,34);//numbers in paranthesis are amount of levels
?>`
KaHa6uc at abv dot bg
13-Mar-2005 09: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 10: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));
// get image size (not exactly)
$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;
// get start point for text
$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));
// create image
$im = imagecreatetruecolor($x, $y);
@imageantialias($im, true);
$bg = imagecolorallocate ($im, $bgr, $bgg, $bgb);
$tx = imagecolorallocate ($im, $r, $g, $b);
#imagecolortransparent ($im, $bg);
imagefill($im, 0, 0, $bg);
// put text
imagettftext ($im, $size, $angle, $s_x, $s_y, $tx, $font, $text);
// minimize borders
// left
for ($x = 0; $x < imagesx($im); $x++)
{
for ($y = 0; $y < imagesy($im); $y++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$left = $x;
// right
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;
// top
for ($y = 0; $y < imagesy($im); $y++)
{
for ($x = 0; $x < imagesx($im); $x++)
{
if (imagecolorat($im, $x, $y) != $bg) break(2);
}
}
$top = $y;
// bottom
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;
// add margin
$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);
// output
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: http://aka-fotos.de/scripts.php`
rob schifreen
09-Mar-2005 03: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 04: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) {
// sanity checking
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 start odd is true, we copy the 2nd line to the 1st
// if start odd is false, we copy the 1st line to the 2nd
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) {
// just in case we're on the boundary
imagesetpixel($image, $x, $y + 1, $curpixel);
}
}
}
}
return $image;
}
?>`
jon
14-Feb-2005 02: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().`
zuo_yf at yahoo dot com
04-Feb-2005 11: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 11:42
`Two stickfigures with different colors:
<?php
// 0
$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);
// 1
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);
// 2
$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);
// 3
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 02: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 10: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 02: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
28-Nov-2004 05: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
23-Nov-2004 05: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]
07-Nov-2004 08: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 12: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 07: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) {
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
// we don't want this character if it's already in the password
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> ";
// $random = imgsecuregen(5); action='secur'
}
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 12: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);
}
}
}
// "imagecreatefrom...() returns an empty string on failure"
return "";
}
?>`
andreoli dot carlo at libero dot it
31-Aug-2004 03: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 12: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 http://se.php.net/manual/sv/function.imagecolorallocate.php
<?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
// Create a rectangle from 0,0 to 50,50 in $image, with a (vertical) gradient from #000000 to #FFFFFF.
imagecolorgradient($image,0,0,50,50,'000000','FFFFFF');
?>`
Caleb Simonyi-Gindele
30-Jun-2004 07: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 09: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
11-Apr-2004 10: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 09: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 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/`
pigmeu at pigmeu dot net
02-Sep-2003 12: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);
//...`
office at 4point-webdesign dot com
06-Jul-2003 02: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;
}`
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');
?>`
Angus Chung a swinburnemultimediastudent
02-Apr-2003 10: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; // temp image width x 3
$t_h = 333; // temp image height x 3
................
// get and create intermediate image
................
imagecopyresized ($destimage,$srcimage,0,0,0,0,$t_w,$t_h,$width,$height);
// process of the output thumbnail
$t_w2 = round($t_w/3); //148
$t_h2 = round($t_h/3); //111
$destimage2 = imagecreatetruecolor($t_w2,$t_h2); // for output
imagecopyresampled ($destimage2,$destimage,0,0,0,0,$t_w2,$t_h2,$t_w,$t_h);
imagedestroy($destimage);
imageinterlace ($destimage2,1);//progressive jpeg
imagejpeg($destimage2, '', 45);
imagedestroy($destimage2);
.................
?>`
RJ-Gerry at wiu dot edu
07-Mar-2003 12: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 http://fink.sourceforge.net 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
05-Mar-2003 11: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 08: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
16-Jan-2003 10: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).`
webmaster at wutallan dot net
13-Dec-2002 11: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 03: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 10: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
http://yoursite/imagegen.php?text=home&h=40&w=150&fontsize=13 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`
06-Mar-2001 11: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){
//Open the gif file to resize
$srcImage = ImageCreateFromGif( $image );
//obtain the original image Height and Width
$srcWidth = ImageSX( $srcImage );
$srcHeight = ImageSY( $srcImage );
// the follwing portion of code checks to see if
// the width > height or if width < height
// if so it adjust accordingly to make sure the image
// stays smaller then the $newWidth and $newHeight
if( $srcWidth < $srcHeight ){
$destWidth = $newWidth * $srcWidth/$srcHeight;
$destHeight = $newHeight;
}else{
$destWidth = $newWidth;
$destHeight = $newHeight * $srcHeight/$srcWidth;
}
// creating the destination image with the new Width and Height
$destImage = imagecreate( $destWidth, $destHeight);
//copy the srcImage to the destImage
ImageCopyResized( $destImage, $srcImage, 0, 0, 0, 0, $destWidth, $destHeight, $srcWidth, $srcHeight );
//create the gif
ImageGif( $destImage );
//fre the memory used for the images
ImageDestroy( $srcImage );
ImageDestroy( $destImage );
}
//save output to a buffer
ob_start();
//Resize image ( will be stored in the buffer )
ResizeGif( "/where/image/is/image.gif", "150", "150");
//copy output buffer to string
$resizedImage = ob_get_contents();
//clear output buffer that was saved
ob_end_clean();
//write $resizedImage to Database, file , echo to browser whatever you need to do with it<BR><BR>Also do not put Header() between ob_start and ob_end_clean() because they will still be sent. $resizedImage is the resized image had there been no ob function calls ResizeGif() would have sent the output to the browser.I hope this helps some people with databases that want to store there image <BR><BR>Dave`
add a note
gd_info iis_stop_service

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 10:36:09 2007 PST