|
|
 |
getimagesize (PHP 3, PHP 4, PHP 5) getimagesize -- Get the size of an image Descriptionarray getimagesize ( string filename [, array &imageinfo] )
The getimagesize() function will determine the
size of any GIF, JPG,
PNG, SWF,
SWC, PSD,
TIFF, BMP,
IFF, JP2,
JPX, JB2,
JPC, XBM, or
WBMP 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.
If accessing the filename image is impossible,
or if it isn't a valid picture, getimagesize()
will return FALSE and generate an error of level
E_WARNING.
Note:
Support for JPC, JP2,
JPX, JB2,
XBM, and WBMP became available in
PHP 4.3.2. Support for SWC exists as of PHP 4.3.0
and TIFF support was added in PHP 4.2.0
Note:
JPEG 2000 support was added in PHP 4.3.2. 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.
Note:
The getimagesize() function does not require the GD
image library.
Returns an array with 4 elements. Index 0 contains the width of
the image in pixels. Index 1 contains the height. Index 2 is a
flag indicating the type of the image: 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. These values correspond to
the IMAGETYPE constants that were added in PHP 4.3.0. Index 3 is a text
string with the correct height="yyy" width="xxx" string that can be used
directly in an IMG tag.
Example 1. getimagesize (file) |
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>
|
|
URL support was added in PHP 4.0.5
Example 2. getimagesize (URL) |
<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");
?>
|
|
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.
Beginning with PHP 4.3.0, bits and
channels are present for other image types, too.
However, 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.
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.
Beginning with PHP 4.3.0, getimagesize() also returns an
additional parameter, mime, that corresponds with the
MIME type of the image. This information can be used to deliver images
with correct HTTP Content-type headers:
Example 3. getimagesize() and MIME types |
<?php
$size = getimagesize($filename);
$fp=fopen($filename, "rb");
if ($size && $fp) {
header("Content-type: {$size['mime']}");
fpassthru($fp);
exit;
} else {
}
?>
|
|
The optional imageinfo 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
http://www.iptc.org/ information in the
APP13 marker. You can use the iptcparse()
function to parse the binary APP13 marker into something
readable.
Example 4. getimagesize() returning IPTC |
<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
$iptc = iptcparse($info["APP13"]);
var_dump($iptc);
}
?>
|
|
See also image_type_to_mime_type(),
exif_imagetype(),
exif_read_data(), and
exif_thumbnail().
User Contributed Notes
getimagesize
irregular at inbox dot ru
30-Apr-2005 06: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
$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);
$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) {
header("Content-type: image/jpeg");
imagejpeg($cachedim,'',100);
}
else {
list($width, $height, $type, $attr) = getimagesize($img);
if ($type==2) {
$im = @imagecreatefromjpeg($img); if (!$im) { $im = imagecreate(150, 30); $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
{
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 03:30
A simple piece of code i wrote to proportionally resize an image to a max height and width then display it
<?php
$max_width = 100;
$max_height = 100;
$upfile '/path/to/file.jpg';
Header("Content-type: image/jpeg");
$size = GetImageSize($upfile); $width = $size[0];
$height = $size[1];
$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;
}
ini_set('memory_limit', '32M');
$src = ImageCreateFromJpeg($upfile);
$dst = ImageCreateTrueColor($tn_width, $tn_height);
ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
ImageJpeg($dst);
ImageDestroy($src);
ImageDestroy($dst);
?>
mail at soylentgreens dot com
30-Mar-2005 08:37
How about this for cropping images...
<?php
$imgfile = "img.jpg";
$cropStartX = 300;
$cropStartY = 250;
$cropW = 200;
$cropH = 200;
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);
list($width, $height) = getimagesize($imgfile);
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);
header("Content-type: image/jpeg");
imagejpeg($cropimg);
imagedestroy($cropimg);
imagedestroy($origimg);
?>
Coodiss at w3bbix dot net
15-Mar-2005 11: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; $heightscale = $iy/175; 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
12-Feb-2005 10: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...
hu dot php dot net at benjamin dot hu
04-Jan-2005 11:06
Flash compressed format SWF:
Array
(
[0] => 468
[1] => 60
[2] => 13
[3] => width="468" height="60"
[mime] => application/x-shockwave-flash
)
[2] : SWC = SWF-compressed value 13
sixzero4 at hotmail dot com
29-Nov-2004 10: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_once('getid3.php');
$getID3 = new getID3;
$file_location = './your/path/to/file.mov';
$fileinfo = $getID3->analyze($file_location);
getid3_lib::CopyTagsToComments($fileinfo);
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.
nonick AT 8027 DOT org
16-Nov-2004 04:46
To: webmaster at theotherpixel dot com
I think the problem is that getimagesize() expects a valid path into the filesystem, so most probably you should use something like:
$ret = getimagesize('/home/whoever/public_html/images/filename');
of course, using the route which applies to your setup: '/usr/www/', whatever.
________
Miguel.
Geoff Vane
13-Nov-2004 12:39
WARNING:
I couldn't get getimagesize() to work when using certain arrays.
The solution was simple but easily overlooked:
When using an array and/or a .txt file,
to store & extract an image filename,
which getimagesize() should examine,
an almost unnoticable and unwanted space can exist !!!
(at the end of the string..)
Use rtrim($yourfilenamestring) to get rid of the space
that will block your getimagesize() operation.
example:
$a = getimagesize(rtrim($yourfilenamestring) ) ;
$a[0] will contain the width
$a[1] will contain the height
:)
webmaster at theotherpixel dot com
19-Sep-2004 09:29
I had one heck of a time using this function under 4.3.0. Searching the web I found a few comments about it just not working, but no solutions. In the long run I copied the page I was using as a test onto another server which was set up the same as the first server. Still no luck. However, I did finally figure out the problem.
It appears that the problem is in not using a relative pathname to the file...
$size = "/images/imagename.gif";
resulted in no results in $size[3].
$size = "http://domain.com/images/imagename.gif";
also gave no results.
On a whim I tried
$size = "images/imagename.gif";
and lo and behold I got my string back.
This seems like a bug to me and perhaps it has been fixed by now, however, this may help someone else when having a similar experience.
Brian
Joshua
16-Aug-2004 02: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
11-Aug-2004 01: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 03: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
25-May-2004 04:36
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?
$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>
<?
$dh = opendir($localDir);
while (false !== ($filename = readdir($dh))) {
$filesArray[] = $filename;
}
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 05: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
10-Mar-2004 08: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 09:11
A cool resize / cropping script for creating thumbnails using mogrify
IMAGETEST.PHP
<?php
include 'mogrify.php';
$picture="sample.jpg";
$fixedwidth=300;
$fixedheight=240;
cropimage($picture,$fixedwidth,$fixedheight,$mogrify);
?>
MOGRIFY.PHP
<?php
$mogrify="C:/apache/Imagik/mogrify.exe";
function cropimage($picture,$fixedwidth,$fixedheight,$mogrify) {
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
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");
$img = imagecreatefromjpeg($picture);
$width= imagesx($img);
$height= imagesy($img);
}
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
01-Dec-2003 08: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
18-Nov-2003 08: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
09-Oct-2003 05: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 $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
03-Sep-2003 11: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)
01-Sep-2003 12: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];
}
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
15-Aug-2003 03: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
30-May-2003 07: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
05-Mar-2003 11: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.
tightcode_nosp@m_hotmail
13-Mar-2002 09:16
If you are using a php version with the bug where GetImageSize returns nothing on certain types of jpeg images, the following replacement should solve the problem until you have upgraded.
It accuratly duplicates the 1st and 2nd array element which are the ones I personally needed. I however added the 4th array element and a crude implementation of the 3rd since some people may need the functionality or find it usefull.
I hopefully reformated the function to not be wordwrapped and it is worth noting that as it is written, it only will work on local files. Additional error checking may be wise.
function sgetimagesize($filename) {
$ftype_array = array(".gif"=>"1",
".jpg"=>"2",
".jpeg"=>"2",
".png"=>"3",
".swf"=>"4",
".psd"=>"5",
".bmp"=>"6");
if (is_file($filename)) {
$fd = @fopen($filename,"r");
$image_string = fread($fd,filesize($filename));
$im = ImageCreateFromString($image_string);
$ftype = $ftype_array[get_file_ext($filename)];
$gis[0] = ImageSX($im);
$gis[1] = ImageSY($im);
$gis[2] = ($ftype?$ftype:"0");
$gis[3] = "width={$gis[0]} height={$gis[1]}";
ImageDestroy($im);
return $gis_array;
}
else { return false; }
}
Cheers,
Tightcode
mogster at boomdesign dot no
09-Mar-2002 12: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...
knutm
| |