|
|
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
You may wish to enhance GD to deal with different fonts. The following
font libraries are supported:
Таблица 2. Supported font libraries
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 был собран с
поддержкой этого расширения или же в том случае, если
данное расширение подгружается во время выполнения.
Пример 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.
sportifenforme at hotmail dot com
04-Oct-2007 06:24
Hi,
Few day ago, i had the same problem with the memory limit.
You can try ini_set('memory_limit', '20M') for trying to upload an image and resize it.
joachim dt werner a diggin-data dt de
29-Aug-2007 11:44
In reply to diggertadmin at gmail dot com:
I had the effect that my thumbnail script exceeded the memory limit, too.
However, as error_reporting was turned off, Firefox just printed out the script URL.
Internet Explorer was more helpful here.
diggertadmin at gmail dot com
23-Jul-2007 09:14
This rather cryptic pair of errors --
"PHP Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 2304 bytes)
Only 0 bytes were written, expected to write 5119 in Unknown"
-- turned out to have a trivial explanation. All it means is that /tmp ran out of free space.
maps at cwsol dot com
22-Apr-2007 12:28
If you are getting the generic error "The image cannot be displayed, because it contains errors.", comment out header("Content-type: image/png");. This will enable PHP to display the real PHP errors.
felipe dot medeiros at kanashii dot com dot br
26-Mar-2007 10:41
Jonathon Reinhart, don't assume it.
.SO and .A files are libraries for dynamic and stactic linking when you compile a program. just to install <package> isn't enought to compile against it's libraries, as them may be only run-time libraries and give you some headache. The correct is to install <package>-devel, which will give you the right libraries for compile time.
And one final word... linux is by now a stable system with lots of working done... if the thing you're trying to do is too hard or unexplained it means that either you're trying something noone ever cared about spending his time on it or you didn't readed how to do it properly. Either way try to learn more about what you're trying.
Jonathon dot Reinhart at DONTSPAMgmail dot com
12-Mar-2007 11:48
I've seen a lot of issues with getting PHP compiled with jpeg and png support. I built it under SuSE 10.2 and ./configure kept giving me "libjpeg.(a|so) not found". I believe that's because my libjpeg was libjpeg.so.62. It also did this for libpng (which mine was named libpng12.so)
Apparently ./config is looking only for the .so files. To resolve this, I installed libjpeg-devel and libpng-devel, which then created symlinks: libpng.so -> libpng12.so and libjpeg.so -> libjpeg.so.62.0.0 . I'm assuming creating these symlinks without installing the -devel packages will work just fine.
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.
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(){
$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);
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
function chunk_image_horizontally ($image, $chunks = 1)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
$chunk_size = round($image_width / $chunks);
for ($current_chunk = 1; $current_chunk < $chunks; $current_chunk++) {
$chunk_images[$current_chunk - 1] = imagecreate($chunk_size, $image_height);
imagecopy($chunk_images[$current_chunk - 1], $image, 1, 1, $chunk_size * ($current_chunk - 1) + 1 , 1, $chunk_size, $image_height);
}
$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 $chunk_images;
}
$in_image = imagecreatefromjpeg('./image.jpg');
$images = chunk_image_horizontally($in_image, 4);
$count = 0;
foreach ($images as $image) {
$count++;
imagejpeg($image, './test_chunk'.$count.'.jpg');
}
?>
g8z at yahoo dot com
19-Jul-2006 01:36
<?php
function change_color($image, $old_color, $new_color, $threshold = 15)
{
$image_width = imagesx($image);
$image_height = imagesy($image);
for ($x = 0; $x < $image_width; $x++) {
for ($y = 0; $y < $image_height; $y++) {
$pixel_color = imagecolorat($image, $x, $y);
if (($pixel_color <= $old_color + $threshold) && ($pixel_color >= $old_color - $threshold)) {
imagesetpixel($image, $x, $y, $new_color);
}
}
}
}
$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;
$biWidth = imagesx ($im);
$biHeight = imagesy ($im);
$biBPLine = $biWidth * 3;
$biStride = ($biBPLine + 3) & ~3;
$biSizeImage = $biStride * $biHeight;
$bfOffBits = 54;
$bfSize = $bfOffBits + $biSizeImage;
fwrite ($f, 'BM', 2);
fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));
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
$var = '#FFFFFF';
function getRgbFromGd($color_hex) {
return array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));
}
print_r(getRgbFromGd($var));
?>
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
header("Content-type: image/gif");
$fontsize = 18;
if(@$_GET['fontsize']) {
$fontsize = $_GET['fontsize'];
}
$font = 'yourcustomfont.ttf';
$text = @$_GET['text'];
$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);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefttext($im, $fontsize, 0, 0, abs($size[5]), $black, $font, $text);
imagegif($im);
imagedestroy($im);
?>
relsqui at chiliahedron dot com
17-Feb-2006 11:14
<?php
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
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;
}
breed_colors(hexdec("012345"), hexdec("6789ab"));
?>
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);
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);
}
$font = imageloadfont($site_font_path."/".$site_font_validation);
imagestring($image, $font, 3, 0, $rand, $textColor);
header("Expires: Mon, 23 Jul 1993 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');
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
$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);
$x_jump = $y_jump = 3;
$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>";
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>";
} echo "</tr><tr>\r\n"; } }
?>
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';
cmyk2rgb($file);
$file = str_replace('.', '-rgb.', $file);
to300dpi($file);
$file = str_replace('.', '-300.', $file);
tiff2jpg($file);
$file = str_replace('.tif', '.jpg', $file);
to300dpi($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';
cmyk2rgb($file);
$file = str_replace('.', '-rgb.', $file);
to300dpi($file);
$file = str_replace('.', '-300.', $file);
tiff2jpg($file);
$file = str_replace('.tif', '.jpg', $file);
to300dpi($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.
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
|
|
|