查看: 12937|回复: 0
打印 上一主题 下一主题

PHP函数getimagesize()

[复制链接]
跳转到指定楼层
1#
发表于 2008-4-6 19:46:49 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
台州网址导航
getimagesize
(PHP 4, PHP 5)

getimagesize — 取得图像大小

说明
array getimagesize ( string $filename [, array &$imageinfo ] )
getimagesize() 函数将测定任何 GIF,JPG,PNG,SWF,SWC,PSD,TIFF,BMP,IFF,JP2,JPX,JB2,JPC,XBM 或 WBMP 图像文件的大小并返回图像的尺寸以及文件类型和一个可以用于普通 HTML 文件中 IMG 标记中的 height/width 文本字符串。

如果不能访问 filename 指定的图像或者其不是有效的图像,getimagesize() 将返回 FALSE 并产生一条 E_WARNING 级的错误。

Note: 对 JPC,JP2,JPX,JB2,XBM 和 WBMP 的支持自 PHP 4.3.2 起可用。对 SWC 的支持自 PHP 4.3.0 起可用。对 TIFF 的支持是 PHP 4.2.0 添加的。


Note: JPEG 2000 支持是 PHP 4.3.2 添加的。注意 JPC 和 JP2 可以有不同的色彩深度的成分。此情况下,“bits”的值是碰到的最高的位深度。此外,JP2 文件可能包含有多个 JPEG 2000 代码流,此情况下,getimagesize() 返回此文件顶层中碰到的第一个代码流的值。

Note: 本函数不需要 GD 图像库。

返回一个具有四个单元的数组。索引 0 包含图像宽度的像素值,索引 1 包含图像高度的像素值。索引 2 是图像类型的标记: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。这些标记与 PHP 4.3.0 新加的 IMAGETYPE 常量对应。索引 3 是文本字符串,内容为“height="yyy" width="xxx"”,可直接用于 IMG 标记。

Example#1 getimagesize(文件)

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

URL 支持是 PHP 4.0.5 添加的。

Example#2 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");

?>

对于 JPG 图像,还会多返回两个索引:channels 和 bits。channels 对于 RGB 图像其值为 3,对于 CMYK 图像其值为 4。bits 是每种颜色的位数。

自 PHP 4.3.0 起,bits 和 channels 对于其它图像类型也存在。但是这些值可能会把人搞糊涂。例如,GIF 总是对每个像素使用 3 个 channel,但是对于动画 GIF 来说每个像素的位数无法通过全局颜色表计算出来。

某些格式可能不包含图像或者包含多个图像。此种情况下,getimagesize() 可能不能用来准确测定图像的大小。此时 getimagesize() 将返回零作为宽度和高度。

自 PHP 4.3.0 起,getimagesize() 还会返回额外的参数 mime,符合该图像的 MIME 类型。此信息可以用来在 HTTP Content-type 头信息中发送正确的信息:

Example#3 getimagesize() 和 MIME 类型

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

可选的 imageinfo 参数允许从图像文件中提取一些扩展信息。目前,这将以一个关联数组返回不同的 JPG APP 标识。某些程序用这些 APP 标识来在图像中嵌入文本信息。一个非常常见的是 APP13 标识中嵌入的 IPTC &raquo; http://www.iptc.org/ 信息。可以用 iptcparse() 函数来将二进制的 APP13 标识解析为可读的信息。


Example#4 getimagesize() 返回 IPTC

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

参见 image_type_to_mime_type(),exif_imagetype(),exif_read_data() 和 exif_thumbnail()。




image_type_to_extension gd_info
--------------------------------------------------------------------------------
Last updated: Mon, 26 Nov 2007
  
add a note User Contributed Notes
getimagesize
info at alex-lawrence dot com
02-Apr-2008 09:17
Could be useful (didn&acute;t know where to post it):

function getImageErrors( $filename, $type = "", $minWidth = 0, $minHeight = 0, $maxWidth = 0, $maxHeight = 0, $maxFileSize = 0 )
{
    $errors = array();
    if ( file_exists( $filename ) )
    {
        $ending = substr( $filename, strpos( $filename, "." ) );
        if ( is_array( $type ) )
        {
            $isTypeOf = false;
            foreach( $type as $eachtype )
            {
                if ( $ending == $eachtype )
                {
                    $isTypeOf = true;
                }
            }
            if ( ! $isTypeOf )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        elseif ( $type != "" )
        {
            if ( $ending != $type )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        $size = getimagesize( $filename );
        if ( $size[ 0 ] < $minWidth )
        {
            $errors[ 'minWidth' ] = $size[ 0 ];
        }
        if ( $size[ 1 ] < $minHeight )
        {
            $errors[ 'minHeight' ] = $size[ 1 ];
        }
        if ( ( $maxWidth > $minWidth ) && ( $size[ 0 ] > $maxWidth ) )
        {
            $errors[ 'maxWidth' ] = $size[ 0 ];
        }
        if ( ( $maxHeight > $minHeight ) && ( $size[ 1 ] > $maxHeight ) )
        {
            $errors[ 'maxHeight' ] = $size[ 1 ];
        }
        if ( ( $maxFileSize > 0 ) && ( filesize( $filename ) > $maxFileSize ) )
        {
            $errors[ 'maxFileSize' ] = filesize( $filename );
        }
    }
    else
    {
        $errors[ 'filename' ] = "not existing";
    }
    return ( count( $errors ) > 0 ? $errors : null );
}
cloned at clonedmadman dot com
26-Feb-2008 06:01
Well, I am making a script which will resize the image when uploaded, however, i am making a multi-uploader, so i came across with a problem: an efficient way of getting a pictures height and width and storing them in an array to resize later. This is what i came up with:

<?php
$links = array("test1.jpg", "test2.png");
$sizearray = array();
$count = count($links);
for($i = 0; $i < $count; $i++) {
    $size = getimagesize($links[$i]);
    list($width, $height) = $size;
    $sizearray[$links[$i]] = array("width" => $width, "height" => $height);
}
print_r($sizearray);
// which will print out: Array ( [test1.jpg] => Array ( [width] => 300 [height] => 400 ) [test2.png] => Array ( [width] => 680 [height] => 100 ) )
?>
shmohel at gmail dot com
12-Feb-2008 10:27
Rather than making a lengthy function that essentially runs twice (once as width, once as height) I came up with a helpful function that uses variable variables to set a maximum height/width. Hope someone finds this helpful.

function scaleimage($location, $maxw=NULL, $maxh=NULL){
    $img = @getimagesize($location);
    if($img){
        $w = $img[0];
        $h = $img[1];

        $dim = array('w','h');
        foreach($dim AS $val){
            $max = "max{$val}";
            if(${$val} > ${$max} && ${$max}){
                $alt = ($val == 'w') ? 'h' : 'w';
                $ratio = ${$alt} / ${$val};
                ${$val} = ${$max};
                ${$alt} = ${$val} * $ratio;
            }
        }

        return("<img src='{$location}' alt='image' width='{$w}' height='{$h}' />");
    }
}
Anonymous
28-Jan-2008 01:14
// A way to maintain Aspect Ratio
// Here using standard aspect ratio of 4:3 for landscape and 3:4 for portrait.
// example is 50% image resize

//NewWidth = GivenHeight * (OriginalWidth / OriginalHeight)
//NewHeight = GivenWidth * (OriginalHeight / OriginalWidth)
        
$defaultImageWidth = 160; //your gallery image width
$defaultImageHeight = 120; //your gallery image height

$imageWidth = 462; // use getimagesize() to get image width
$imageHeight = 432; // use getimagesize() to get image height
   
if($imageWidth > $imageHeight)
{
    // landscape image
   
    $newWidth = $defaultImageWidth;
    $newHeight = (int)($defaultImageWidth * $imageHeight / $imageWidth);
   
    if($newHeight > $defaultImageHeight)
    {
        $newHeight = $defaultImageHeight;
        $newWidth = (int)($defaultImageHeight * $imageWidth / $imageHeight);
    }

}
elseif ($imageHeight > $imageWidth)
{
    // portrait image
   
    $newHeight = $defaultImageHeight;
    $newWidth = (int)($defaultImageHeight * $imageWidth / $imageHeight);
   
    if($newWidth > $defaultImageWidth)
    {
        $newWidth = $defaultImageWidth;
        $newHeight = (int)($defaultImageWidth * $imageHeight / $imageWidth);
    }
   
}
else
{
    // square image
   
    $newWidth = $defaultImageWidth;
    $newHeight = $defaultImageHeight;
   
}

// here using Image Magick command line utility to resize image, OR you can use some other package.
//@exec("/usr/local/bin/convert $sourceImageFilePath - -resize $newWidthx$newHeight\! $destinationImageFilePath");

echo '<b>New Width:</b>'.$newWidth;
echo "<br>";
echo '<b>New Height:</b>'.$newHeight;
pfarthing at hotmail dot com
11-Jan-2008 07:35
Correction: to find $y2 it should be...

// set y side to a proportional size
$y2 = $m * $x_max; // not $x1

Thanks Norbert =)
info at personalmis dot com
07-Jan-2008 08:42
Seems the various ways people are trying to proportionaly scale an image, up or down, could be more straight forward if one remembers ones algebra.

The formula is, y = mx, where m is the slope of the line. This is the ratio of y:x or m = y/x.

So if...

// max values for x and y
$y_max = 600;
$x_max = 800;

// image size
$y1 = 2000;
$x1 = 3000;

// use width for scaling
if ($x1 > $x_max)
{
    // find slope
    $m = $y1/$x1;
    // set x side to max
    $x2 = $x_max;
    // set y side to a proportional size
    $y2 = $m * $x1;
}

The new image proportionally scaled will be x2 = 800, y2 = 533 (rounded).

To do it from the y side, simply reverse the x's and y's.
redcore at gmail dot com
10-Aug-2007 05: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
04-Aug-2007 02: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 />';
?>
phpnetUNDERSCOREspam at erif dot org
19-Jun-2007 03: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 09: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;
}
jens at kulmegies dot de
31-Oct-2006 10: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]...
egingell at sisna dot com
06-May-2006 06: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 11: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
John
06-Feb-2006 03:57
I was coming here to see if there was a simple way to get the height, width, and mime type of an image I have uploaded and while I thought the following code would work because it is printed above
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
?>

it didnt when I tried to echo out $type; so heres my fix, there may be a better way but it works for me!

<?php
$blah = getimagesize("folder/file.gif");
$type = $blah['mime'];
$width = $blah[0];
$height = $blah[1];
?>

and then you can just echo out one of the variables about to get whichever you would desire.
gormozus at yahoo dot com
16-Nov-2005 02:56
getimagesize() seems to cache the results, so if you resize an image (using the methods described earlier) and you want to re-read its width and height, use imagesx() and imagesy() to get the actual information.
webmaster at WWW.ELLESSEWEB.NET
26-Oct-2005 08:10
This is a useful function to display a thumbnail of a whatever image.
This piece of code has been lightly modified from an example found on <b>NYPHP.ORG</B>.
This function can build a thumbnail of any size you want and display it on your browser!
Hope it can be useful for you guys!

<?php

function makeThumbnail($o_file, $t_ht = 100) {
    $image_info = getImageSize($o_file) ; // see EXIF for faster way
   
    switch ($image_info['mime']) {
        case 'image/gif':
            if (imagetypes() & IMG_GIF)  { // not the same as IMAGETYPE
                $o_im = imageCreateFromGIF($o_file) ;
            } else {
                $ermsg = 'GIF images are not supported<br />';
            }
            break;
        case 'image/jpeg':
            if (imagetypes() & IMG_JPG)  {
                $o_im = imageCreateFromJPEG($o_file) ;
            } else {
                $ermsg = 'JPEG images are not supported<br />';
            }
            break;
        case 'image/png':
            if (imagetypes() & IMG_PNG)  {
                $o_im = imageCreateFromPNG($o_file) ;
            } else {
                $ermsg = 'PNG images are not supported<br />';
            }
            break;
        case 'image/wbmp':
            if (imagetypes() & IMG_WBMP)  {
                $o_im = imageCreateFromWBMP($o_file) ;
            } else {
                $ermsg = 'WBMP images are not supported<br />';
            }
            break;
        default:
            $ermsg = $image_info['mime'].' images are not supported<br />';
            break;
    }
   
    if (!isset($ermsg)) {
        $o_wd = imagesx($o_im) ;
        $o_ht = imagesy($o_im) ;
        // thumbnail width = target * original width / original height
        $t_wd = round($o_wd * $t_ht / $o_ht) ;

        $t_im = imageCreateTrueColor($t_wd,$t_ht);
        
        imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
        
        imageJPEG($t_im);
        
        imageDestroy($o_im);
        imageDestroy($t_im);
    }
    return isset($ermsg)?$ermsg:NULL;
}
?>

Here the code to call the function:

<?

header("Content-type: image/jpeg");
makeThumbnail("http://it2.php.net/images/php.gif", 300);

?>
Mark at Mild Peril
13-Oct-2005 07:54
To solve the problem with using absolute site filepaths, as experienced by Brian:

$size = getimagesize($_SERVER["DOCUMENT_ROOT"].$file);

(where $file is something like "/rootdir/graphics/photo.jpg")
paul at goldenbakery dot nl
05-Aug-2005 05:02
Note that the canvas of a Flash movie can not be empty for getimagesize() to read the dimensions of an SWF. Not sure if this is a bug, a feature or just a limitation of the SWF format.

Flash version does not seem to matter. Also tested with Flash 8 beta.
Sean
31-May-2005 01:23
I needed a quick way to make a group of images uniformly sized, but only on one page.  So creating a new set of thumbnails was overdoing the whole thing.  I made up this script that seems to do the trick.

<?php
     $image =  "absolute/path/to/image/image.jpg";               
     $size = getimagesize("$image");
       $height = $size[1];
       $width = $size[0];
     if ($height > 150)
          {
               $height = 150;
               $percent = ($size[1] / $height);
               $width = ($size[0] / $percent);
          }
     else if ($width > 150)
          {
               $width = 150;
               $percent = ($size[0] / $width);
               $height = ($size[1] / $percent);
          }
     echo "<img src\"image/path/image.jpg\" height=\"$height\" width=\"$width\" />";
?>
irregular at inbox dot ru
30-Apr-2005 07:24
I've wrote this piece of useful code.
May be it will be useful for you.
But i got a problem - if source image is in the area with need of authorization then the functions that read some files from that place (i.e. getimagesize, imagejpeg) does not work!
How to solve it?

<?php
//i't a stand-alone file named resize.php
//the feature is caching
// /image/thumbcache folder is used with file name forming by md5($img.$calc_width.$calc_height);
//it gets such parameters:
//img - image address (URL)
//w - optional width
//h - optional height
//if you set either w or h, then the image is resized proportionaly, according to the source
//if you set neither w nor h then the script just output file
//if you set both w or h then the image will be resized exactly how you want

    $server_root = 'http://'.$_SERVER['SERVER_NAME'].'/';

    if (isset($_GET['img']) && ((isset($_GET['w']) || isset($_GET['h'])))
    {
        $img = substr($_GET['img'],0,100);
        if (isset($_GET['w'])) $w = substr($_GET['w'],0,10);
        if (isset($_GET['h'])) $h = substr($_GET['h'],0,10);

        error_reporting(0);

        //check cache
        $hash = md5($img.$w.$h);
        $pos = strrpos($img,".");
        $ext = substr($img,$pos+1,strlen($img)-$pos);
        $fname = $hash.'.'.$ext;
        $cachedim = @imagecreatefromjpeg($serverroot.'images/thumbcache/'.$fname);
        if ($cachedim) //just show cached thumbnail
        {
            header("Content-type: image/jpeg");
            imagejpeg($cachedim,'',100);
        }
        else //create and cache thumbnail and show it 'cause it's not in cache
        {
            list($width, $height, $type, $attr) = getimagesize($img);
            if ($type==2) //jpeg
            {
                $im = @imagecreatefromjpeg($img); /* Attempt to open */
                if (!$im) { /* See if it failed */
            $im  = imagecreate(150, 30); /* Create a blank image */
                    $bgc = imagecolorallocate($im, 255, 255, 255);
                    $tc  = imagecolorallocate($im, 0, 0, 0);
                    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
                    imagestring($im, 1, 5, 5, "Error loading image!", $tc);
                }
                else
                {
                    //constrain proportions if needed
                    if (isset($w)){ if ($w==0) $w = $width; }
                    else $w = $width*$h/$height;

                    if (isset($h)){ if ($h==0) $h = $height; }
                    else $h = $height*$w/$width;

                    $dstw=isset($w)?$w:$width;
                    $dsth=isset($h)?$h:$height;
                    $tim = imagecreatetruecolor($dstw,$dsth);
            
            imagecopyresampled($tim,$im,0,0,0,0,$dstw,$dsth,$width,$height);
                    
                    header("Content-type: image/jpeg");
                    imagejpeg($tim,'./images/thumbcache/'.$fname,100);
                    imagejpeg($tim,'',100);
                }
            }
        }
        error_reporting(E_ALL);
    }

?>
ajreading at classixshop dot com
21-Apr-2005 04:30
A simple piece of code i wrote to proportionally resize an image to a max height and width then display it

<?php
// Max height and width
$max_width = 100;
$max_height = 100;

// Path to your jpeg

$upfile '/path/to/file.jpg';
    Header("Content-type: image/jpeg");
   
    $size = GetImageSize($upfile); // Read the size
          $width = $size[0];
          $height = $size[1];
         
          // Proportionally resize the image to the
          // max sizes specified above
         
          $x_ratio = $max_width / $width;
          $y_ratio = $max_height / $height;

          if( ($width <= $max_width) && ($height <= $max_height) )
          {
               $tn_width = $width;
               $tn_height = $height;
          }
          elseif (($x_ratio * $height) < $max_height)
          {
               $tn_height = ceil($x_ratio * $height);
               $tn_width = $max_width;
          }
          else
          {
               $tn_width = ceil($y_ratio * $width);
               $tn_height = $max_height;
          }
     // Increase memory limit to support larger files
     
     ini_set('memory_limit', '32M');
     
     // Create the new image!
     $src = ImageCreateFromJpeg($upfile);
     $dst = ImageCreateTrueColor($tn_width, $tn_height);
     ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
     ImageJpeg($dst);
// Destroy the images
ImageDestroy($src);
ImageDestroy($dst);
?>
mail at soylentgreens dot com
31-Mar-2005 10:37
How about this for cropping images...

<?php

$imgfile = "img.jpg";
$cropStartX = 300;
$cropStartY = 250;
$cropW   = 200;
$cropH   = 200;

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// TODO: write code to save new image
// or, just display it like this:
header("Content-type: image/jpeg");
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);

?>
Coodiss at w3bbix dot net
16-Mar-2005 01:51
Heres a easy way to scale images to the <td> that they are in
*this is broken up so anyone can understand it :)

<?
$imageinfo = getimagesize("images/picture.jpg");
         
$ix=$imageinfo[0];
$iy=$imageinfo[1];

$widthscale = $ix/175;  //<TD> WIDTH
$heightscale = $iy/175; //<TD> HEIGHT

if($widthscale < 1)
$nwidth = $ix*$widthscale;
else
$nwidth = $ix/$widthscale;

if($heightscale < 1)
$nheight = $iy*$heightscale;
else
$nheight = $iy/$heightscale;

?>
php dot net at dannysauer dot com
13-Feb-2005 12:23
Note that, if you're going to be a good programmer and use named constatnts (IMAGETYPE_JPEG) rather than their values (2), you want to use the IMAGETYPE variants - IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, etc.  For some reason, somebody made a horrible decision, and IMG_PNG is actually 4 in my version of PHP, while IMAGETYPE_PNG is 3.  It took me a while to figure out why comparing the type against IMG_PNG was failing...
sixzero4 at hotmail dot com
30-Nov-2004 12:33
This is just to add to the comment by robertks at hotmail dot com on
05-Mar-2003 12:12 regarding trying to derive the dimensions of a video file. The package referenced (http://www.getid3.org/) had been updated, and below is a script I use to get the size. You can get many other attributes of media files as well.

<?php
// include getID3() library (can be in a different directory if full path is specified)
include_once('getid3.php');

// Initialize getID3 engine
$getID3 = new getID3;

// File to get info from
$file_location = './your/path/to/file.mov';

// Get information from the file
$fileinfo = $getID3->analyze($file_location);
getid3_lib::CopyTagsToComments($fileinfo);

// Output results
if (!empty($fileinfo['video']['resolution_x'])) { echo '<p> video width: '.$fileinfo['video']['resolution_x'].'</p>'; }
if (!empty($fileinfo['video']['resolution_y'])) { echo '<p> video height: '.$fileinfo['video']['resolution_y'].'</p>'; }
?>

Hope that helps others looking for a function similar to getimagesize() for a video or media file.
Joshua
17-Aug-2004 03:26
If your image name has spaces in it you will need to use rawurlencode() and NOT urlencode() as this function (at least in 4.3.4) does not accept spaces as + signs.
cstdenis at hotmail dot com
12-Aug-2004 02:42
This will not work for swf files unless zlib is compiled into php statically (not as a shared module). Bug #29611

As of PHP 5.0.0 it will just return false, but that should change to a notice by the next release.
ryan at vitalmodels dot com
05-Jun-2004 04:06
--- Editor's Note:
It's easier to call on urlencode() or rawurlencode() to "fix" urls containing spaces and other characters that normally not well-liked.
---

You may have noticed that images with spaces WONT work with getimagesize - some of us have massive amounts of pictures, or don't feel like rewriting file names on users uploaded pictures- so here is a super fast fix that will replace the spaces once the image is called and will work with getimagesize flawlessly-

$image_new = "/pictures/$pic[picture]";  //PICTURE URL
$image_new = str_replace(' ','%20',$image_new); //REPLACE THE SPACES

Now you just call $image_new using getimagesize and you wont' have anymore problems.

On my site I take uploaded pictures from users - then resize them if they are over a certain width, here is the script i use if anyone would like to do this-

$image_new = "/pictures/$pic[picture]"; //url of picture
$image_new = str_replace(' ','%20',$image_new); //take url and replace spaces
$max_width= "480";  //maximum width allowed for pictures
$resize_width= "480";  //same as max width
$size = getimagesize("$image_new");    //get the actual size of the picture
$width= $size[0];           // get width of picture
$height= $size[1];   // get height of picture
if ($width>$max_width){
            $new_width=$resize_width;  // Resize Image If over max width
}else {
            $new_width=$width;       // Keep original size from array because smaller than max

}

echo "<IMG src=\"$image_new\" border=1  width=$new_width>"   //print image with new width

Hope this helps anyone who wants some simple uses for getimagesize- check out my website to see it in action- vitalmodels.com
diablx at hotmail dot com
26-May-2004 05:36
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?
    // Some configuration variables !
    $maxWidth = 90;
    $maxHeight = 90;
    $maxCols = 8;
    $webDir = "https://localhost/images/";
    $localDir = $_SERVER['DOCUMENT_ROOT']."/images/";

    $AutorisedImageType = array ("jpg", "jpeg", "gif", "png");
?>

<center>
<table border='1' cellspacing='5' cellpadding='5' style="border-collapse:collapse; border-style: dotted">
<tr>
   <?
   // Open localDir
   $dh = opendir($localDir);
   while (false !== ($filename = readdir($dh))) {
       $filesArray[] = $filename;
   }

   // Display and resize
   foreach ($filesArray as $images) {
   
       $ext = substr($images, strpos($images, ".")+1, strlen($images));
      
       if( in_array($ext, $AutorisedImageType) ) {

           list($width, $height, $type, $attr) = @getimagesize( $localDir.$images );

            $xRatio = $maxWidth / $width;
            $yRatio = $maxHeight / $height;
            
            if ( ($width <= $maxWidth) && ($height <= $maxHeight) ) {
              $newWidth = $width;
              $newHeight = $height;
            }
            else if (($xRatio * $height) < $maxHeight) {
              $newHeight = ceil($xRatio * $height);
              $newWidth = $maxWidth;
            }
            else {
              $newWidth = ceil($yRatio * $width);
              $newHeight = $maxHeight;
            }
           
           if($i == $maxCols) {
               echo "</tr><tr>";
               $i = 0;
           }
           echo "<td align='center' valign='middle' width='$maxWidth' height='$maxHeight'><img src='".$webDir.$images."' width='$newWidth' height='$newHeight'></td>";
           $i++;
       }
   }
?>
</tr>
</table>
</center>
MagicalTux at FF.st
31-Mar-2004 07:35
simm posted something interesting about imagick, but usually calling an external binary is not the best way.

You can use the Imagick PHP module . With it, you do not even need to get the image size to generate thubnails...

Here's the code I used :
<?php
    $imh=imagick_readimage($image);
    imagick_scale($imh,GALLERY_THUMBNAILWIDTH,GALLERY_THUMBNAILHEIGHT);
    imagick_writeimage($imh,$image_thumb);
?>

(I noticed that some hosting companies are now providing the imagick module by default. Using it allows you to accept any type of image from your visitors. Maybe it will be documented on the official PHP website one day or another? )
MarioPro
11-Mar-2004 10:13
The Problem:
I've just noticed that after upgrading to the PHP 4.3.4 version, the old GetImageSize() should get your attention on pages coded before this new version.

The solutions:
So, if you used GetImageSize(), you should now be using getimagesize() - attention to all lower caracters.

Also, you shou certify that the image realy exists, otherwhise you'll get the following error: getimagesize(): Read error!
This means that there is no image to "fill" the string and thus you're calling, for example: "images/news/" instead of calling "images/news/03102004a.jpg"

One should now verify if there is an image to be called (example):
if($photo1!=""){
$size1=getimagesize("images/news/".$photo_news_1"]);
$width1=$size1[0];
$height1=$size[1];
}
Here, if $photo_news_1 is set and exists it will be displayed, otherwhise it will be skiped and no ERROR message will be displayed. In the PHP 4.3.3 and earlier versions, this was not necessary but it is now!  ;)
yohami dot com - zerodj at hotmail dot com
14-Jan-2004 11:11
A cool resize / cropping script for creating thumbnails using mogrify

IMAGETEST.PHP

<?php

include 'mogrify.php';

// variables from flash (my website uses flash and php)
$picture="sample.jpg";
$fixedwidth=300;
$fixedheight=240;
//

cropimage($picture,$fixedwidth,$fixedheight,$mogrify);

?>

MOGRIFY.PHP

<?php
// walking the path
$mogrify="C:/apache/Imagik/mogrify.exe";

// ---------------------------------------- crop function

function cropimage($picture,$fixedwidth,$fixedheight,$mogrify) {

    // GET IMG
    $img = imagecreatefromjpeg($picture);
    $width= imagesx($img);
    $height= imagesy($img);
    // CROP WIDTH
    if($width!=$fixedwidth){
        $ratio =$fixedwidth/$width;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
        // REFRESH
        $img = imagecreatefromjpeg($picture);
        $width= imagesx($img);
        $height= imagesy($img);
    }
    // CROP HEIGHT
    if($height!=$fixedheight){
        $ratio =$fixedheight/$height;
        $NewHeight=round($height*$ratio);
        $NewWidth=round($width*$ratio);
        exec( $mogrify." -resize ".$NewWidth."x".$NewHeight."! $picture");
        exec( $mogrify." -crop ".$fixedwidth."x".$fixedheight."+0+0 $picture");
    }
    //
    ImageDestroy($img);
}

?>

yeah!
php (at) thejpster org uk
02-Dec-2003 10:39
If you want to resize an image proportionally to fit within a given area, like I did, the following code might help you out.

If either hscale or wscale are greater than 1 then that dimension is too big. If you then scale your image by the larger of the two values (hscale, wscale) then you guarantee that both dimensions will now fit in your specified area :)

function makeImg($num) {
    global $hmax, $wmax; // max width and height
    $image = "somefile.jpg";
    list($width, $height, $type, $attr) = getimagesize($image);
    $hscale = $height / $hmax;
    $wscale = $width / $wmax;
    if (($hscale > 1) || ($wscale > 1)) {
        $scale = ($hscale > $wscale)?$hscale:$wscale;
    } else {
        $scale = 1;
    }
    $newwidth = floor($width / $scale);
    $newheight= floor($height / $scale);

    return "<img width='$newwidth' height='$newheight' src='$image'><br>$image: $newwidth x $newheight : $width x $height";
}
djwishbone at hotmail dot com
19-Nov-2003 10:31
Using remote files with getimagesize($URL) never worked for me.  Except when I would grab files from the same server.  However, I developed some code with the help from the people here that does work.  If you are having problems give this function a shot:

function getimagesize_remote($image_url) {
    $handle = fopen ($image_url, "rb");
    $contents = "";
    if ($handle) {
    do {
        $count += 1;
        $data = fread($handle, 8192);
        if (strlen($data) == 0) {
            break;
       }
    $contents .= $data;
    } while(true);
    } else { return false; }
    fclose ($handle);

    $im = ImageCreateFromString($contents);
    if (!$im) { return false; }
    $gis[0] = ImageSX($im);
    $gis[1] = ImageSY($im);
// array member 3 is used below to keep with current getimagesize standards
    $gis[3] = "width={$gis[0]} height={$gis[1]}";
    ImageDestroy($im);
    return $gis;
}

goodluck
janoma_cl
10-Oct-2003 06:19
If you want to show thumbnails keeping the original proportions, with defined maximum width and height, you can use this function. This is useful when showing tables of user-uploaded images, that not necessarily are same-sized. However, for big images (like wallpapers), a better option is to create separated thumbnails with a image-editing software.

If the image is smaller or equal than the defined maximums, then it's showed without resizing. If not, creates a link to a pop-up that shows the full-size image.

<?php
function show_thumbnail($file)
{
    $max = 200 // Max. thumbnail width and height

    $size = getimagesize($file);

    if ( $size[0] <= $max && $size[1] <= $max )
    {
        $ret = '<img src="'.$file.'" '.$size[3].' border="0">';
    }
    else
    {
        $k = ( $size[0] >= $size[1] ) ? $size[0] / $max : $size[1] / $max;
        $ret = '<a href="javascript:;" onClick="window.open(\'image.php?img=';
        $ret .= $file.'\',\'\',\'width='.$size[0];
        $ret .= ',height='.$size[1].'\')">';
        $ret .= '<img src="'.$file.'" width="'.floor($size[0]/$k).'" height="'.floor($size[1]/$k).'" border="0" alt="View full-size image"></a>';
    }

    return $ret;
}
?>

Here is the code of 'image.php':

<html>
<head>
<title>Image</title>
</head>
<body leftmargin="0" topmargin="0">
<?php echo ( is_file($_GET['img']) ) ? '<a href="#" onClick="window.close();"><img src="'.$_GET['img'].'" border="0" alt="Close window"></a>' : 'Invalid image filename, or no filename entered. <a href="#" onClick="window.close();">Close window</a>.' ?>
</body>
</html>
simms
04-Sep-2003 12:47
here's a nice way of resizing user-uploaded files on the fly, using ImageMagick (on linux), but no GD:

<?

if( $image_info = getimagesize( "/upload_dir/" . $uploadName ) )
{
  if( $image_info[ 0 ] > $defaultImgWidth )
  {
    exec( "mogrify -geometry " . $defaultImgWidth . " " . "/upload_dir/" . $uploadName . " &" );
  }
}

?>

$defaultImgWidth would be the target width of the image -- note that the code above resizes the image without distorting its original proportions, and only if it is wider than $defaultImgWidth.
the ImageMagick syntax used above ("mogrify ..") overwrites the original file ($uploadName) with the resized image.
ten tod xmg ta rotanimrev (reverse it)
02-Sep-2003 01:30
An additional note to "tightcode_nosp@m_hotmail":

If that doesn't work try this instead:

<?
      $img = imagecreatefromjpeg ($filename);
      $x = imagesx ($img);
      $y = imagesy ($img);
      imagedestroy ($img);
?>

Though keep in mind that this consumes lots of CPU. So if you're doing something like creating a page of thumbnails this is considerably slower.

So what you can do is use getimagesize() and check if
- the width and height are empty strings ("")
- and those two values aren't too high

Both indicate that getimagesize() didn't work properly. The latter may happen if getimagesize() thought that it recognized the format and therefore the size properly. I mean if you're looking at pictures that you know are max. 1024x768 and getimagesize() returns a width of e.g. 20234 then it's obvious that something went wrong. In that case use the code mentioned above. Of course if getimagesize() returned small values that are wrong you still get the wrong size. So check your pictures and priorities first.

So all of this could look like as follows:

<?
    $picinfo = @getimagesize ($filename);
    if ($picinfo !== false) {
      $x = $picinfo [0];
      $y = $picinfo [1];
    }

    // change this according the picture resolutions you're expecting
    if ($x > 2000 || $y > 2000) $x = $y = "";

    if ($x == "") {
      $img = imagecreatefromjpeg ($filename);
      $x = imagesx ($img);
      $y = imagesy ($img);
      imagedestroy ($img);
    }
?>

Note: fix syntax stuff if there's an error as I compiled this example from a few places.

If you don't care about the huge load on your CPU or you have to rely on the proper size use the snippet noted at the beginning only.
justin at webtekconcepts dot com
16-Aug-2003 04:27
For those that like to go the dynamic thumbnail route, I've found that you can get warnings with getimagesize() after your loop through more than 3 to 4 images. In my case I needed 12 images on each page.

Use usleep() in your loop just before you run getimagesize() otherwise you'll end up with warnings, big images and a broken page. Using usleep() lets the server recoup for X milliseconds so it will accept connections again for the image size.

I've found that usleep(1500) is the best for my situation. This barely slows the page down and allows for getimagesize() to work 100% of the time for me.
webmaster AT theparadox DOT org
31-May-2003 08:16
I figured others have wanted to scale an image to a particular height or width while preserving the height/width ratio. So here are the functions I wrote to accomplish this. Hopefully they'll save somebody else the five minutes it took to write these.

You give the filename and the dimension you want to use, and these functions return the opposite dimension:

function scale_to_height ($filename, $targetheight) {
   $size = getimagesize($filename);
   $targetwidth = $targetheight * ($size[0] / $size[1]);
   return $targetwidth;
}
         
function scale_to_width ($filename, $targetwidth) {
   $size = getimagesize($filename);
   $targetheight = $targetwidth * ($size[1] / $size[0]);
   return $targetheight;
}
robertks at hotmail dot com
06-Mar-2003 01:12
For those of you trying to derive the dimensions of a video file (e.g. Video for Windows AVI, Quicktime MOV, MPEG MPG, Windows Media Video WMV or ASF, etc.), you will find the getid3 library to be indispensible.  Found at http://getid3.sourceforge.net, here's an example of its use in a script:

include_once('getid3.php'); // or wherever you actually put the getid3 scripts
$file_location = './myvideo.avi';
$file_info = GetAllFileInfo($file_location) // calls getid3 function
$file_width = $file_info['video']['resolution_x'];
$file_height = $file_info['video']['resolution_y'];

You can then use your OBJECT and EMBED tags in HTML to put the video into a web page, and make the PHP template independent of the size parameters of the particular video it happens to be loading.  (Just remember to add pixels to the video height to accomodate the controller of the embedded player: typically, 16 pixels for Quicktime, 46 pixels for Windows Media Player 6, and 64 pixels for Windows Media Player 7.
mogster at boomdesign dot no
10-Mar-2002 02:58
Really useful info from webmasterb@feartheclown.com and you others :-)
Saved my butt...
Here's a build on that, with proportional resizing of the image-upload ($newpic) to a fixed value ($maxwidth):
$maxwidth = "350";
$imagehw = GetImageSize($newpic);
$imagewidth = $imagehw[0];
$imageheight = $imagehw[1];
$imgorig = $imagewidth;
if ($imagewidth > $maxwidth {
  $imageprop=($maxwidth*100)/$imagewidth;
  $imagevsize= ($imageheight*$imageprop)/100 ;
  $imagewidth=$maxwidth;
  $imageheight=ceil($imagevsize);
}
Of course this does not resize the image itself, but returns values one may use in html-code to restrain users from killing your design...
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 转播转播 分享分享 分享淘帖
台州维博网络(www.tzweb.com)专门运用PHP+MYSQL/ASP.NET+MSSQL技术开发网站门户平台系统等。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

网站推广
关于我们
  • 台州维博网络(Tzweb.com)拥有多年开发网站平台系统门户手机客户端等业务的成功经验。主要从事:企业网站建设、网站程序开发、手机APP客户端、平面设计、主机域名、虚拟空间、网站推广、网站优化、后期维护等服务,满足不同企业公司的需求,是台州地区领先的网络技术服务商!

Hi,扫描关注我

Copyright © 2005-2024 站长论坛 All rights reserved

Powered by 站长论坛 with TZWEB Update Techonolgy Support

快速回复 返回顶部 返回列表