Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

getimagesize

(PHP 3, PHP 4, PHP 5)

getimagesize -- Get the size of an image

Описание

array getimagesize ( string filename [, array &imageinfo] )

The getimagesize() function will determine the size of any given image file and return the dimensions along with the file type and a height/width text string to be used inside a normal HTML <IMG> tag and the correspondant HTTP content type.

getimagesize() can also return some more information in imageinfo parameter.

Замечание: Note that JPC and JP2 are capable of having components with different bit depths. In this case, the value for "bits" is the highest bit depth encountered. Also, JP2 files may contain multiple JPEG 2000 codestreams. In this case, getimagesize() returns the values for the first codestream it encounters in the root of the file.

Список параметров

filename

imageinfo

This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Возвращаемые значения

Returns an array with 5 elements.

Index 0 and 1 contains respectively the width and the height of the image.

Замечание: Some formats may contain no image or may contain multiple images. In these cases, getimagesize() might not be able to properly determine the image size. getimagesize() will return zero for width and height in these cases.

Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.

Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

mime is the correspondant MIME type of the image. This information can be used to deliver images with correct the HTTP Content-type header:

Пример 1. getimagesize() and MIME types

<?php
$size
= getimagesize($filename);
$fp = fopen($filename, "rb");
if (
$size && $fp) {
   
header("Content-type: {$size['mime']}");
   
fpassthru($fp);
    exit;
} else {
   
// error
}
?>

channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color. However, for some image types, the presence of these values can be a bit confusing. As an example, GIF always uses 3 channels per pixel, but the number of bits per pixel cannot be calculated for an animated GIF with a global color table.

On failure, FALSE is returned.

Errors/Exceptions

If accessing the filename image is impossible, or if it isn't a valid picture, getimagesize() will generate an error of level E_WARNING.

Список изменений

ВерсияОписание
4.3.2 Support for JPC, JP2, JPX, JB2, XBM, and WBMP became available.
4.3.2 JPEG 2000 support was added for the imageinfo parameter.
4.3.0 bits and channels are present for other image types, too.
4.3.0 mime was added.
4.3.0 Support for SWC was added.
4.2.0 Support for TIFF was added.
4.0.5 URL support was added.

Примеры

Пример 2. getimagesize (file)

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo
"<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Пример 3. getimagesize (URL)

<?php
$size
= getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Пример 4. getimagesize() returning IPTC

<?php
$size
= getimagesize("testimg.jpg", $info);
if (isset(
$info["APP13"])) {
   
$iptc = iptcparse($info["APP13"]);
   
var_dump($iptc);
}
?>

Примечания

Замечание: The getimagesize() function does not require the GD image library.



image_type_to_extension> <gd_info
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
getimagesize
redcore at gmail dot com
09-Aug-2007 02:50
It's always good to check out an image's dimensions while attempting to upload to your server or database...especially if it's going to be displayed on a page that doesn't accomodate images beyond a particular size.

<?php

$tmpName
= $_FILES['userfile']['tmp_name'];
       
list(
$width, $height, $type, $attr) = getimagesize($tmpName);

if(
$width>275 || $height>275)
{
die(
"exceeded image dimension limits.");
}

?>
laurens dot stoetzel at gmail dot com
03-Aug-2007 11:18
In reply to John (http://de.php.net/manual/de/function.getimagesize.php#61514):
list will only work with numeric arrays.

<?php
 
//renumber
 
$my_image = array_values(getimagesize('test.jpg'));
 
//use list on new array
 
list($width, $height, $type, $attr) = $my_image;

 
//view new array
 
print_r($my_image);

 
//spit out content
 
echo 'Attribute: '.$attr.'<br />';
  echo
'Width: '.$width.'<br />';
?>
way2sirius
09-Jul-2007 11:09
Or, you could check that the image file exists before calling the function:

$is  = null;
$pic = 'path/to/image.jpg';

if( file_exists($pic) )
{
    $is = getimagesize($pic);
}
geoff at spacevs dot com
01-Jul-2007 09:33
In reply to the below suggestion:

<?php
    
print("<!--");
   
$is = getimagesize($pic);
     print(
"-->");
?>

This is nasty as the client still will receive the warning, just commented out in the HTML, you can just prefix "getimagesize" with an "@" to suppress any errors or warnings.

Eg:

<?PHP
  $is
= @getimagesize($pic);
?>
tim at dataxpress dot net
01-Jul-2007 01:16
I'm working on files on a server where I can't change the php configuration.  I wanted to use this with files that potentially weren't images / broken URLs.

When this fails it returns an E_Warning, but you can also check for failure if the width or height are 0. 
 
I wanted to use my own system for telling the user that there was an error, but I couldn't figure out how to hide the php E_Warning error...

until i thought of this!
  <?php
      
print("<!--");
     
$is = getimagesize($pic);
       print(
"-->");
 
?>

=D figured this might be useful for somebody else having the same problem.
phpnetUNDERSCOREspam at erif dot org
19-Jun-2007 12:26
an alternative to the three options below for finding the width and height of data you know to be an image:

$image = imagecreatefromstring($mydata);
$width = imagesx($image);
$height = imagesy($image);
boshka at gmail dot com
01-Feb-2007 05:40
I was trying to workaround with the problem of getting the mime type of the image from the raw data (the images data is stored in a database and the mime type is not known in advance). Since getimagesize requires a file name, there are some ways to deal with it:
1. call getimagesize with a URL which points to the image - this is too slow.
2. use PHP file i/o wrapper class.
3. use temporary files. The code for #3 could be as follows:

    function getimagesize_raw($data){
        $cwd = getcwd(); #get current working directory
        $tempfile = tempnam("$cwd/tmp", "temp_image_");#create tempfile and return the path/name (make sure you have created tmp directory under $cwd
        $temphandle = fopen($tempfile, "w");#open for writing
        fwrite($temphandle, $data); #write image to tempfile
        fclose($temphandle);
        $imagesize = getimagesize($tempfile); #get image params from the tempfile
        unlink($tempfile); // this removes the tempfile
        return $imagesize;
}
jlratwil at yahoo dot com
08-Nov-2006 05:10
Data types of the output array for getimagesize().

[0] = The width of the image. It is integer data type.
[1] = The height of the image. It is an integer data type.
[2] = Image Type Flag. It is an integer data type.
[3] = String for <img> tag (width="xxx" height="xxx"). It is a string data type.
[bits] = Number of bits. It is an integer data type.
[channels] = Number of channels. It is an integer data type.
[mime] = MIME type. It is a string data type.
jens at kulmegies dot de
31-Oct-2006 06:30
In addition to thomporter's quick-reference of the output array, here's what PHP 4.4.0 does:

Array[0] = Width
Array[1] = Height
Array[2] = Image Type Flag
Array[3] = width="xxx" height="xxx"
Array[bits] = bits
Array[channels] = channels
Array[mime] = mime-type

There is no chance of getting the mime-type by accessing Array[6]...
thomporter.com
22-Oct-2006 09:16
Every time I come here I'm bothered by the fact that there's no quick reference to the indexes of the array returned by this function.  It's all wrapped up in a paragraph, hard to find.  So, here it is:

Array[0] = Width
Array[1] = Height
Array[2] = Image Type Flag
Array[3] = width="xxx" height="xxx"
Array[4] = channels (PHP >= 4.3.0)
Array[5] = bits (PHP >= 4.3.0)
Array[6] = mime (PHP >= 4.3.0)
zusto at nextra dot sk
10-Aug-2006 02:30
For nonick AT 8027 DOT org (16-Nov-2004 11:46)

You can use GET parameter ($_GET["photo_url"]) as the function variable and when you will need to make some thumbnail, you can specify the path in the url of image... something like "<img src = "url/for/thumb_function_page.php?photo_url=photos/originals/image.jpg" ...>
php at cNO_SOLICITATIONbreak dot org
18-May-2006 01:49
Apparently appending $attr in the <img ...> tag will not render the image at all or render only a portion of the image under Safari and IE under certain circumstances.

I haven't figured out the exact circumstances, but I'm using XHTML 1.0 Transitional DTD, and the circumstances seem to depend on the rendering order of the page. The problem is due to the width="..." attribute in general, not the height="..." attribute.

To fix the problem, forget the $attr attribute and stick with the stylesheet:

  <?php list($w, $h) = getimagesize("image.jpg") ?>
  <img src="image.jpg" style="width: <?php=$w?>px; height: <?php=$h?>px;" />
egingell at sisna dot com
06-May-2006 03:14
<?

// These constants are used by image_info(), below.
define ('IMAGE_WIDTH', 'width');
define ('IMAGE_HEIGHT', 'height');
define ('IMAGE_TYPE', 'type');
define ('IMAGE_ATTR', 'attr');
define ('IMAGE_BITS', 'bits');
define ('IMAGE_CHANNELS', 'channels');
define ('IMAGE_MIME', 'mime');

/**
 * mixed image_info( file $file [, string $out] )
 *
 * Returns information about $file.
 *
 * If the second argument is supplied, a string representing that information will be returned.
 *
 * Valid values for the second argument are IMAGE_WIDTH, 'width', IMAGE_HEIGHT, 'height', IMAGE_TYPE, 'type',
 * IMAGE_ATTR, 'attr', IMAGE_BITS, 'bits', IMAGE_CHANNELS, 'channels', IMAGE_MIME, and 'mime'.
 *
 * If only the first argument is supplied an array containing all the information is returned,
 * which will look like the following:
 *
 *    [width] => int (width),
 *    [height] => int (height),
 *    [type] => string (type),
 *    [attr] => string (attributes formatted for IMG tags),
 *    [bits] => int (bits),
 *    [channels] => int (channels),
 *    [mime] => string (mime-type)
 *
 * Returns false if $file is not a file, no arguments are supplied, $file is not an image, or otherwise fails.
 *
 **/
function image_info($file = null, $out = null) {

    // If $file is not supplied or is not a file, warn the user and return false.
    if (is_null($file) || !is_file($file)) {
        echo '<p><b>Warning:</b> image_info() => first argument must be a file.</p>';
        return false;
    }

    // Defines the keys we want instead of 0, 1, 2, 3, 'bits', 'channels', and 'mime'.
    $redefine_keys = array(
        'width',
        'height',
        'type',
        'attr',
        'bits',
        'channels',
        'mime',
    );

    // If $out is supplied, but is not a valid key, nullify it.
    if (!is_null($out) && !in_array($out, $redefine_keys)) $out = null;

    // Assign usefull values for the third index.
    $types = array(
        1 => 'GIF',
        2 => 'JPG',
        3 => 'PNG',
        4 => 'SWF',
        5 => 'PSD',
        6 => 'BMP',
        7 => 'TIFF(intel byte order)',
        8 => 'TIFF(motorola byte order)',
        9 => 'JPC',
        10 => 'JP2',
        11 => 'JPX',
        12 => 'JB2',
        13 => 'SWC',
        14 => 'IFF',
        15 => 'WBMP',
        16 => 'XBM'
    );
    $temp = array();
    $data = array();

    // Get the image info using getimagesize().
    // If $temp fails to populate, warn the user and return false.
    if (!$temp = getimagesize($file)) {
        echo '<p><b>Warning:</b> image_info() => first argument must be an image.</p>';
        return false;
    }

    // Get the values returned by getimagesize()
    $temp = array_values($temp);

    // Make an array using values from $redefine_keys as keys and values from $temp as values.
    foreach ($temp AS $k => $v) {
        $data[$redefine_keys[$k]] = $v;
    }

    // Make 'type' usefull.
    $data['type'] = $types[$data['type']];

    // Return the desired information.
    return !is_null($out) ? $data[$out] : $data;   
}

?>
Russell Chappell
31-Mar-2006 07:01
For those of you who are confused about what the mime type IE displays image/pjpeg and other browsers image/jpeg and are building in checks for all of your scripts to tell the difference i would suggest using the getimagesize() mime results which will always be image/jpeg regardless what browser you use.

<?php
$info
= getimagesize("image.jpg");
foreach(
$info as $key => $value) {
    echo
$key . ' - ' . $value . '<br />';
}
?>

Where it says mime always is image/jpeg
mail AT sascha MINUS diebel DOt de
22-Feb-2006 06:55
Note that with JPG images, two extra indexes are returned: channels and bits. channels will be 3 for RGB pictures and 4 for CMYK pictures. bits is the number of bits for each color.

Bei JPG Bildern werden 2 zus
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571