Portrety Uliczne Nieznajomych - zobacz wyjątkową galerię portretów z warszawskich ulic
ZALOGUJ SIĘ
login:
hasło:
przypomnij hasło
załóż konto użytkownika
(i zobacz kilka porad gratis)
   
WYSZUKIWARKA I DZIAŁY
całe porady  tytuły
zaznacz działy do przeszukania
(brak wyboru = wszystkie działy)
PHP
MySQL >
PostgreSQL
SQLite
Perl
Java
XML
XSLT
XPath
WML
SVG
RegExp
Wyszukiwarki
Ochrona
VBScript
Google Plus
XHTML/CSS
JavaScript
Grafika
Flash
Photoshop
Windows
Linux
Bash
Apache
Procmail
E-biznes
Explorer
Opera
Firefox
Inne porady
   
KURSY, DOKUMENTACJE
Własne:
XHTML/CSS
JavaScript
ActionScript
WML, RSS, SSI
Pozostałe:
PHP
MySQL
Java API
więcej...
   
użytkowników online: 16
W CZYM MOGĘ POMÓC?


   
OPINIE UŻYTKOWNIKÓW
Przyznam, że jestem pod sporym wrażeniem. Od wielu lat zajmuje się grafiką przeznaczoną do druku ze szczególnym uwzględnieniem opakowań. Z radością stwierdzam, iż twórca serwisu jest moim ulubionym typem potencjalnego współpracownika (choć branża troszeczkę inna) tzn. pada pytanie i błyskawicznie pada konkretna odpowiedź bez względu na stopień skomplikowania pytania. Gorąco polecam współpracę, gdyż macie pewność że nie zostaniecie potraktowani sloganami typu "oczywiście", "nie ma sprawy" tylko otrzymacie konkretną pomoc. Tak trzymać! Na pewno jeszcze nie raz skorzystam

Paweł
Studio Gama

   
GALERIA FOTOGRAFII
   
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net

[Spis] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [X] [W] [Z]

LII. Image Functions

Wstęp

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.

Notatka: Read requirements section about how to expand image capabilities to read, write and modify images and to read meta data of pictures taken by digital cameras.

Wymagania

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.

Notatka: 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.

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

Tabela 1. Supported image formats

Image formatLibrary to downloadNotes
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 avaliable since PHP 4.3.9 and PHP 5.0.1.
jpeg-6bftp://ftp.uu.net/graphics/jpeg/ 
pnghttp://www.libpng.org/pub/png/libpng.html Only supported in GD versions greater than gd-1.6.
xpmftp://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:

Tabela 2. Supported font libraries

Font libraryDownloadNotes
FreeType 1.xhttp://www.freetype.org/ 
FreeType 2http://www.freetype.org/ 
T1libftp://sunsite.unc.edu/pub/Linux/libs/graphics/) Support for Type 1 fonts.

If you have PHP compiled with --enable-exif 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 as mentioned above. These functions do not require the GD library.

Instalacja

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.

Notatka: To enable exif support in Windows, php_mbstring.dll must be loaded prior to php_exif.dll in php.ini.

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.

Tabela 3. Supported image formats

Image FormatConfigure 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.

Notatka: 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.

Tabela 4. Supported font libraries

Font libraryConfigure 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 (Type 1 fonts) add --with-t1lib[=DIR].
Native TrueType string function To enable support for native TrueType string function add --enable-gd-native-ttf.

Konfiguracja czasu wykonywania

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

Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.

Stałe predefinopwane

Poniższe stałe są zdefiniowane w tym rozszerzeniu i stają się dostępne, gdy rozszerzenie jest dokompilowane do PHP, lub załadowane dynamicznie przy starcie.

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)

Przykłady

Przykład 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.

Spis treści
gd_info -- Retrieve information about the currently installed GD library
getimagesize -- Get the size of an image
image_type_to_extension --  Get file extension for image type
image_type_to_mime_type -- Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype
image2wbmp -- Output image to browser or file
imagealphablending -- Set the blending mode for an image
imageantialias --  Should antialias functions be used or not
imagearc -- Draw a partial ellipse
imagechar -- Draw a character horizontally
imagecharup -- Draw a character vertically
imagecolorallocate -- Allocate a color for an image
imagecolorallocatealpha -- Allocate a color for an image
imagecolorat -- Get the index of the color of a pixel
imagecolorclosest -- Get the index of the closest color to the specified color
imagecolorclosestalpha -- Get the index of the closest color to the specified color + alpha
imagecolorclosesthwb --  Get the index of the color which has the hue, white and blackness nearest to the given color
imagecolordeallocate -- De-allocate a color for an image
imagecolorexact -- Get the index of the specified color
imagecolorexactalpha -- Get the index of the specified color + alpha
imagecolormatch --  Makes the colors of the palette version of an image more closely match the true color version
imagecolorresolve --  Get the index of the specified color or its closest possible alternative
imagecolorresolvealpha --  Get the index of the specified color + alpha or its closest possible alternative
imagecolorset -- Set the color for the specified palette index
imagecolorsforindex -- Get the colors for an index
imagecolorstotal -- Find out the number of colors in an image's palette
imagecolortransparent -- Define a color as transparent
imagecopy -- Copy part of an image
imagecopymerge -- Copy and merge part of an image
imagecopymergegray -- Copy and merge part of an image with gray scale
imagecopyresampled -- Copy and resize part of an image with resampling
imagecopyresized -- Copy and resize part of an image
imagecreate -- Create a new palette based image
imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL
imagecreatetruecolor -- Create a new true color image
imagedashedline -- Draw a dashed line
imagedestroy -- Destroy an image
imageellipse -- Draw an ellipse
imagefill -- Flood fill
imagefilledarc -- Draw a partial ellipse and fill it
imagefilledellipse -- Draw a filled ellipse
imagefilledpolygon -- Draw a filled polygon
imagefilledrectangle -- Draw a filled rectangle
imagefilltoborder -- Flood fill to specific color
imagefilter --  Applies a filter to an image
imagefontheight -- Get font height
imagefontwidth -- Get font width
imageftbbox -- Give the bounding box of a text using fonts via freetype2
imagefttext -- Write text to the image using fonts using FreeType 2
imagegammacorrect -- Apply a gamma correction to a GD image
imagegd2 -- Output GD2 image to browser or file
imagegd -- Output GD image to browser or file
imagegif -- Output image to browser or file
imageinterlace -- Enable or disable interlace
imageistruecolor -- Finds whether an image is a truecolor image
imagejpeg -- Output image to browser or file
imagelayereffect --  Set the alpha blending flag to use the bundled libgd layering effects
imageline -- Draw a line
imageloadfont -- Load a new font
imagepalettecopy -- Copy the palette from one image to another
imagepng -- Output a PNG image to either the browser or a file
imagepolygon -- Draw a polygon
imagepsbbox --  Give the bounding box of a text rectangle using PostScript Type1 fonts
imagepscopyfont --  Make a copy of an already loaded font for further modification
imagepsencodefont -- Change the character encoding vector of a font
imagepsextendfont -- Extend or condense a font
imagepsfreefont -- Free memory used by a PostScript Type 1 font
imagepsloadfont -- Load a PostScript Type 1 font from file
imagepsslantfont -- Slant a font
imagepstext -- To draw a text string over an image using PostScript Type1 fonts
imagerectangle -- Draw a rectangle
imagerotate -- Rotate an image with a given angle
imagesavealpha --  Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images
imagesetbrush -- Set the brush image for line drawing
imagesetpixel -- Set a single pixel
imagesetstyle -- Set the style for line drawing
imagesetthickness -- Set the thickness for line drawing
imagesettile -- Set the tile image for filling
imagestring -- Draw a string horizontally
imagestringup -- Draw a string vertically
imagesx -- Get image width
imagesy -- Get image height
imagetruecolortopalette -- Convert a true color image to a palette image
imagettfbbox -- Give the bounding box of a text using TrueType fonts
imagettftext -- Write text to the image using TrueType fonts
imagetypes -- Return the image types supported by this PHP build
imagewbmp -- Output image to browser or file
imagexbm --  Output XBM image to browser or file
iptcembed -- Embed binary IPTC data into a JPEG image
iptcparse --  Parse a binary IPTC http://www.iptc.org/ block into single tags.
jpeg2wbmp -- Convert JPEG image file to WBMP image file
png2wbmp -- Convert PNG image file to WBMP image file



User Contributed Notes

jab
24-Jan-2006 03:02

If you are developing on/for a Windows platform, read this and you might save yourself some time.

The output using 'imagejpeg' and 'imagepng' (other file formats might also be affected) produce LARGE file sizes even if you use 'imagetruecolortopalette' to reduce the number of colors. During tests, image files sizes were 3 to 4 times larger when generated on a Windows platform than on Linux. (PHP Version 4.4.0).
 
Sample JPEG test result:
Original image size: 11.68 KB
Output image size on Linux platform: 8.06 KB
Output image size on Windows platform: 27.51 KB

I strongly recommend that you do NOT use these functions if your server run on a Windows platform and you want to generate multiple images "on-the-fly" for a web site.

<?php

/**
 * Test function to compare png file size
 *
 * @param  $file  absolute path to image file
 * @return  void
 */
function test_png($file)
{
  
$image = imagecreatefrompng($file);
  
imagetruecolortopalette($image, true, 256);
  
header("Content-type: image/png");
  
imagepng($image);
}

/**
 * Test function to compare jpeg file size
 *
 * @param  $file  absolute path to image file
 * @return  void
 */
function test_jpeg($file)
{
  
$image = imagecreatefromjpeg($file);
  
imagetruecolortopalette($image, true, 256);
  
header("Content-type: image/jpeg");
  
imagejpeg($image, "", 60);
}

?>


jan at anh dot sk
15-Jan-2006 01: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 12: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
14-Jan-2006 01: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
06-Jan-2006 02: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
26-Dec-2005 08: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 06: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


raphael at schwarzschmid dot de
24-Nov-2005 04:46

I was looking for some thumbnail creaton facility for my directory listing script (http://schwarzschmid.de/php-directory-listing), but the one posted by lasse84 below didn't quite fit my needs.

Unfortunately the class is too long to post here. If you're interested, get it from http://download.schwarzschmid.de/Thumbnail.class.phps


Jonas Sweden
17-Nov-2005 12: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 11: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 11: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 09: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".


stephan dot klein at gmx dot at
01-Oct-2005 03:40

I was looking for a function to determine whether a variable is a valid image ressource. After a bit of thinking I came up with this pretty fast solution:

<?php
function is_gd_handle($var) {
  
ob_start();
      
imagecolorallocate($var, 255, 255, 255);
      
$error = ob_get_contents();
  
ob_end_clean();
   if(
preg_match('/not a valid Image resource/',$error)) {
       return
false;
   } else {
       return
true;
   }
}
?>

Hope it saved somebody some time!


lasse84 at host dot sk
19-Sep-2005 11:02

I was trying to write my own photogallery, but could't find a simpel and easy-to-use on-the-fly thumbnail creator with cache ability. So I created JustThumb

I don't want to paste the whole file here so here is a link:
http://jack-the-ripper.mine.nu/justThumb/


someone at somewhere dot com dot au
13-Sep-2005 05:40

If you chose to use the PECL_imagick module in your PHP install rather than GD, check the source tarball for the examples directory for documentation. Other docs are very scarce on the net!


lace at gta dot hu
31-Aug-2005 12:10

To get gdlib working on the windows installation of php do this:

(info from: gdlib site: http://www.boutell.com/gd/faq.html)

[..]
php 4.3.x is available, and it includes a version of gd as "standard equipment." php_gd2.dll is included in a standard PHP installation for Windows, it's just not enabled by default. To turn it on, the user may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension. Change:

#extension=php_gd2.dll

To:

extension=php_gd2.dll

You may also have to correct the extension directory setting from:

extension_dir = "./"

Or:

extension_dir = "./extensions"

To (FOR WINDOWS):

extension_dir = "c:/php/extensions" NOTE: SUBSTITUTE THE ACTUAL PHP INSTALLATION DIRECTORY ON *YOUR* COMPUTER.

Thanks to Benoit Blais for this last point. Thanks also to Alan MacDougall and Perculator.
 
[..]


trucex at gmail
28-Aug-2005 01: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
25-Aug-2005 12: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
19-Aug-2005 12: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 08: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 04: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 04: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.


yasin yyalcinkaya at ku dot edu dot tr
29-Jul-2005 03:43

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;
   }
}   
?>


grzegorz at Mouton dot pl
19-Jul-2005 11:05

how to get a jpg quality from file?


AmX
05-Jul-2005 12: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 09: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 07: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
05-Jun-2005 02:11

Beauty of an example for the gd libary !
http://www.nyphp.org/content/presentations/GDintro

greez
_nu


Adalius
04-Jun-2005 10: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

 

 
  © 1996-2012 & Reporter.plmiejscao serwisieabonamentwarunki korzystaniaRSSkontakt