©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5, PHP 7)
getimagesize — 取得图像大小
$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 » 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() 。
filename
This parameter specifies the file you wish to retrieve information about. It can reference a local file or (configuration permitting) a remote file using one of the supported streams.
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 7 elements.
Index 0 and 1 contains respectively the width and the height of the image.
Note:
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 the correct HTTP Content-type header:
Example #5 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.
For some image types, the presence of channels and bits 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.
If accessing the filename
image is impossible, or
if it isn't a valid picture, getimagesize() will
generate an error of level E_WARNING
. On read error,
getimagesize() will generate an error of level
E_NOTICE
.
版本 | 说明 |
---|---|
5.3.0 | Added icon support. |
5.2.3 |
Read errors generated by this function downgraded to
E_NOTICE from 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 and IFF was added. |
4.2.0 | Support for TIFF was added. |
4.0.6 | Support for BMP and PSD was added. |
4.0.5 | URL support was added. |
Example #6 getimagesize() example
<?php
list( $width , $height , $type , $attr ) = getimagesize ( "img/flag.jpg" );
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />" ;
?>
Example #7 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" );
?>
Example #8 getimagesize() returning IPTC
<?php
$size = getimagesize ( "testimg.jpg" , $info );
if (isset( $info [ "APP13" ])) {
$iptc = iptcparse ( $info [ "APP13" ]);
var_dump ( $iptc );
}
?>
Note:
此函数不需要 GD 图象库。
[#1] simon dot waters at surevine dot com [2015-03-30 09:01:38]
Note: getimage size doesn't attempt to validate image file formats
It is possible for malformed GIF images to contain PHP and still have valid dimensions.
Programmers need to ensure such images are validated by other tools, or never treated as PHP or other executable types (enforcing appropriate extensions, avoiding user controlled renaming, restricting uploaded images to areas of the website where PHP is not enabled).
http://ha.ckers.org/blog/20070604/passing-malicious-php-through-getimagesize/
[#2] kazuya [2014-03-11 02:19:49]
i made function img_resize($path,$tmp_name,$new_name,$new_width)
this could be useful.
<?php
$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";
function img_resize($path,$tmp_name,$new_name,$new_width){
if (!file_exists($path.$filename)){
echo "file not found!";
exit;
}
if (!is_writable($path)){
echo "error:permission denied!";
exit;
}
list($width, $height) = getimagesize($path . $tmp_name);
$new_height = abs($new_width * $height / $width);
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($path . $tmp_name);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$new_width, $new_height, $width, $height);
imagejpeg($image_p, $path . $new_name);
return $path.$new_name;
}
?>
[#3] tomasz at trejderowski dot pl [2013-09-06 09:47:13]
If you want to "convert" value returned by "getimagesize()" as index "2" into something more human-readable, you may consider using a function like this one:
$imageTypeArray = array
(
0=>'UNKNOWN',
1=>'GIF',
2=>'JPEG',
3=>'PNG',
4=>'SWF',
5=>'PSD',
6=>'BMP',
7=>'TIFF_II',
8=>'TIFF_MM',
9=>'JPC',
10=>'JP2',
11=>'JPX',
12=>'JB2',
13=>'SWC',
14=>'IFF',
15=>'WBMP',
16=>'XBM',
17=>'ICO',
18=>'COUNT'
);
$size = getimagesize($filename);
$size[2] = $imageTypeArray[$size[2]];
Or something similar.
[#4] eng dot honey007 at gmail dot com [2013-04-21 02:40:45]
function Get_Image_size($img,$req){
$get = getimagesize($img);
$width = $get[0];
$height = $get[1];
$type = $get[2];
$attr = $get[3];
$bits = $get['bits'];
$mime = $get['mime'];
return $$req;
}
echo Get_Image_size('5.png','attr');
[#5] chris at ocportal dot com [2012-06-18 10:59:45]
Note that animated gifs may have frames width different dimensions. This function will not get the first frame's width/height. GIFs define "Logical Screen Descriptor" dimensions, which are the maximum for all frames.
To get the screen descriptor dimensions, use:
<?php
$header = unpack('@6/vwidth/vheight', $binaryData);
// $header['width'] and $header['width'];
?>
[#6] alexyam at live dot com [2012-02-15 23:30:09]
I wanted to use getimagesize() on .SWF files stored in the database as blob data and couldn't find a simple solution, so I created my own.
I am releasing this code under the MIT license to save everyone some time:
<?php
class blob_data_as_file_stream {
private static $blob_data_position = 0;
public static $blob_data_stream = '';
public static function stream_open($path,$mode,$options,&$opened_path){
static::$blob_data_position = 0;
return true;
}
public static function stream_seek($seek_offset,$seek_whence){
$blob_data_length = strlen(static::$blob_data_stream);
switch ($seek_whence) {
case SEEK_SET:
$new_blob_data_position = $seek_offset;
break;
case SEEK_CUR:
$new_blob_data_position = static::$blob_data_position+$seek_offset;
break;
case SEEK_END:
$new_blob_data_position = $blob_data_length+$seek_offset;
break;
default:
return false;
}
if (($new_blob_data_position >= 0) AND ($new_blob_data_position <= $blob_data_length)){
static::$blob_data_position = $new_blob_data_position;
return true;
}else{
return false;
}
}
public static function stream_tell(){
return static::$blob_data_position;
}
public static function stream_read($read_buffer_size){
$read_data = substr(static::$blob_data_stream,static::$blob_data_position,$read_buffer_size);
static::$blob_data_position += strlen($read_data);
return $read_data;
}
public static function stream_write($write_data){
$write_data_length=strlen($write_data);
static::$blob_data_stream = substr(static::$blob_data_stream,0,static::$blob_data_position).
$write_data.substr(static::$blob_data_stream,static::$blob_data_position+=$write_data_length);
return $write_data_length;
}
public static function stream_eof(){
return static::$blob_data_position >= strlen(static::$blob_data_stream);
}
}
?>
[#7] utilmind [2011-07-23 03:17:49]
Here is the function which determines whether the PNG image contains alpha or not:
<?php
function is_alpha_png($fn){
return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6);
}
?>
The color type of PNG image is stored at byte offset 25. Possible values of that 25'th byte is:
* 0 - greyscale
* 2 - RGB
* 3 - RGB with palette
* 4 - greyscale + alpha
* 6 - RGB + alpha
[#8] Steve [2011-04-17 15:12:00]
The list of defined IMAGETYPE_ constants is on the manual page for exif_imagetype:
http://www.php.net/manual/en/function.exif-imagetype.php
[#9] msfs11 at gmail dot com [2011-04-06 04:07:08]
One more reason of "Error: getimagesize(): Read error!" may be an zero file size. Check the file size first with function filesize( $file ).
[#10] kumarldh at gmail dot com [2011-03-14 01:44:37]
I spent quite a time and realised one needs "allow_url_fopen" turned on to be able to use getimagesize(). Hope this help others.
[#11] Jesus Zamora [2011-02-13 06:20:01]
Returns a array with 4 elements.
The 0 index is the width of the image in pixels.
The 1 index is the height of the image in pixels.
The 2 index is a flag for the image type:
1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.
The 3 index contains ' height="yyy" width="xxx" '
[#12] falkon303 at gmail dot com [2011-02-09 22:01:40]
Here's a simple way to resize your images based on a percentage.
<?php
$image_path = "images/your_image.png";
list($width, $height, $type, $attr)= getimagesize($image_path);
//specify what percentage you are resizing to
$percent_resizing = 80;
$new_width = round((($percent_resizing/100)*$width));
$new_height = round((($percent_resizing/100)*$height));
echo '<img src="'.$image_path.'" height="'.$new_height.'" width="'.$new_width.'">';
?>
[#13] Urchin [2011-02-08 13:00:49]
On a Debian machine I had a lot of Notices in my log because the system did not understand spaces. While the str_replace and rawurlencode options are ok for remote images, for the local system it is of no use.
I used the following:
getimagesize('"'.$location.'"');
so basically I quoted the location (single_quot-dubble_quote-single_quote).
[#14] modnyj at gmail dot com [2010-04-26 04:34:24]
A simple method to resize a image keeping the constraint proportions:
<?php
// Constraints
$max_width = 100;
$max_height = 100;
list($width, $height) = getimagesize($img_path);
$ratioh = $max_height/$height;
$ratiow = $max_width/$width;
$ratio = min($ratioh, $ratiow);
// New dimensions
$width = intval($ratio*$width);
$height = intval($ratio*$height);
?>
[#15] @hill79 [2010-02-18 07:57:09]
I needed to find image dimensions for use in some dynamic css, since getimagesize() returns width="x" height="y" at index 3 I had to convert that to a valid CSS format.
Thought I'd share the function in case anyone else needs the same.
<?php
function cssifysize($img) {
$dimensions = getimagesize($img);
$dimensions = str_replace("=\"", ":", $dimensions['3']);
$dimensions = str_replace("\"", "px;", $dimensions);
return $dimensions;
}
returns width:x;height:y;
?>
I expect there's a way of making that more efficient
[#16] Nikki [2010-01-26 15:26:52]
This should be easy, but I've re-solved the problem so many times. Hopefully this is useful:
<?php
// Usage example to find the proper dimensions to resize an image down to 300x400 pixels maximum:
list($width, $height) = getimagesize($image);
$new_dimensions = resize_dimensions(300,400,$width,$height);
// Calculates restricted dimensions with a maximum of $goal_width by $goal_height
function resize_dimensions($goal_width,$goal_height,$width,$height) {
$return = array('width' => $width, 'height' => $height);
// If the ratio > goal ratio and the width > goal width resize down to goal width
if ($width/$height > $goal_width/$goal_height && $width > $goal_width) {
$return['width'] = $goal_width;
$return['height'] = $goal_width/$width * $height;
}
// Otherwise, if the height > goal, resize down to goal height
else if ($height > $goal_height) {
$return['width'] = $goal_height/$height * $width;
$return['height'] = $goal_height;
}
return $return;
}
?>
[#17] swapnil dot nkene at gmail dot com [2009-12-03 02:08:55]
A simplest method to resize a image keeping the constraint proportions.
<?php
list($width, $height, $type, $attr)=getimagesize($imagepath);
$ht=$height;
$wd=$width;
if($width>180){
$diff = $width-180;
$percnt_reduced = (($diff/$width)*100);
$ht = $height-(($percnt_reduced*$height)/100);
$wd= $width-$diff;
}
if($height>180){
$diff = $height-180;
$percnt_reduced = (($diff/$height)*100);
$wd = $width-(($percnt_reduced*$width)/100);
$ht= $height-$diff;
}
?>
[#18] geoff at spacevs dot com [2009-10-20 23:22:14]
This function returns the width and height of a JPEG image from a string, allowing the dimensions of images stored in a database to be retrieved without writing them to the disk first, or using "imagecreatefromstring" which is very slow in comparison.
<?PHP
function getJPEGImageXY($data) {
$soi = unpack('nmagic/nmarker', $data);
if ($soi['magic'] != 0xFFD8) return false;
$marker = $soi['marker'];
$data = substr($data, 4);
$done = false;
while(1) {
if (strlen($data) === 0) return false;
switch($marker) {
case 0xFFC0:
$info = unpack('nlength/Cprecision/nY/nX', $data);
return array($info['X'], $info['Y']);
break;
default:
$info = unpack('nlength', $data);
$data = substr($data, $info['length']);
$info = unpack('nmarker', $data);
$marker = $info['marker'];
$data = substr($data, 2);
break;
}
}
}
?>
Doing this 10,000 times takes 0.43 seconds, compared with using imagecreatefromstring/imagesx/imagesy which takes around 1.52 seconds to do the same.
Do not use this instead of getimagesize when dealing with files, getimagesize is much faster coming in at 0.15 seconds.
[#19] mycrazydream [2009-07-24 09:00:57]
I had for quite some time been using getimagesize() to check for the existence of a remote image. This turned out to take way too long. The following curl solution only checks the http headers so it is much more efficient.
<?php
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
?>
[#20] anonymous [2009-07-15 13:37:47]
Well there are a lot of image scaling functions here. Here is my take on it.
<?php
function get_scaled_dim_array($img,$max_w = 100, $max_h = NULL){
if(is_null($max_h)){
$max_h = $max_w;
}
if (file_exists($img)){
list($img_w,$img_h) = getimagesize($img);
$f = min($max_w/$img_w, $max_h/$img_h, 1);
$w = round($f * $img_w);
$h = round($f * $img_h);
return array($w,$h);
}
return NULL;
}
?>
[#21] james dot relyea at zifiniti dot com [2009-02-07 20:49:39]
As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:
<?php
// Retrieve JPEG width and height without downloading/reading entire image.
function getjpegsize($img_loc) {
$handle = fopen($img_loc, "rb") or die("Invalid file stream.");
$new_block = NULL;
if(!feof($handle)) {
$new_block = fread($handle, 32);
$i = 0;
if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
$i += 4;
if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
// Read block size and skip ahead to begin cycling through blocks in search of SOF marker
$block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
$block_size = hexdec($block_size[1]);
while(!feof($handle)) {
$i += $block_size;
$new_block .= fread($handle, $block_size);
if($new_block[$i]=="\xFF") {
// New block detected, check for SOF marker
$sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
if(in_array($new_block[$i+1], $sof_marker)) {
// SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
$size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
$unpacked = unpack("H*", $size_data);
$unpacked = $unpacked[1];
$height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
$width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
return array($width, $height);
} else {
// Skip block marker and read block size
$i += 2;
$block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
$block_size = hexdec($block_size[1]);
}
} else {
return FALSE;
}
}
}
}
}
return FALSE;
}
?>
[#22] anonymous [2008-11-23 08:30:55]
Note that if you specify a remote file (via a URL) to check the size of, PHP will first download the remote file to your server.
If you're using this function to check the size of user provided image links, this could constitute a security risk. A malicious user could potentially link to a very large image file and cause PHP to download it. I do not know what, if any, file size limits are in place for the download. But suppose the user provided a link to an image that was several gigabytes in size?
It would be nice if there were a way to limit the size of the download performed by this function. Hopefully there is already a default with some sensible limits.
[#23] user at example dot net [2008-07-23 09:13:29]
When validating images, allways check both, image type *AND* file extension!
Because most image types allow sections for comments or other irrelevant data. Those section can be used to infiltrate php code onto the server. If these files are stored as sent by the client, files with a ".php" extension can be executed and do tremendous harm.
[#24] mike [2008-04-25 16:26:05]
Great script shmohel, a bit more minified...
<?php
function scale_image($p,$mw='',$mh='') { // path max_width max_height
if(list($w,$h) = @getimagesize($p)) {
foreach(array('w','h') as $v) { $m = "m{$v}";
if(${$v} > ${$m} && ${$m}) { $o = ($v == 'w') ? 'h' : 'w';
$r = ${$m} / ${$v}; ${$v} = ${$m}; ${$o} = ceil(${$o} * $r); } }
return("<img src='{$p}' alt='image' width='{$w}' height='{$h}' />"); }
}
?>
[#25] devon at example dot com [2008-04-07 00:14:10]
***********************************
Copies Source Image to Destination Image
***********************************
1. Copies source image
2. Calculates image dimensions
3. Resizes image (you specify max height/width)
4. Retains aspect ratio
5. Writes destination image
***********************************
This was created from a variety of code snippets
I've found here at php.net and other places on the web.
I take no credit for any of this code other than
putting the pieces together.
<?php
$source_pic = 'images/source.jpg';
$destination_pic = 'images/destination.jpg';
$max_width = 500;
$max_height = 500;
$src = imagecreatefromjpeg($source_pic);
list($width,$height)=getimagesize($source_pic);
$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;
}
$tmp=imagecreatetruecolor($tn_width,$tn_height);
imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
imagejpeg($tmp,$destination_pic,100);
imagedestroy($src);
imagedestroy($tmp);
?>
[#26] info at alex-lawrence dot com [2008-04-02 05:17:19]
Could be useful (didn?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 );
}
[#27] cloned at clonedmadman dot com [2008-02-25 14:01:19]
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 ) )
?>
[#28] shmohel at gmail dot com [2008-02-12 06:27:35]
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}' />");
}
}
[#29] Anonymous [2008-01-27 21:14:19]
// 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;
[#30] pfarthing at hotmail dot com [2008-01-10 15:35:44]
Correction: to find $y2 it should be...
// set y side to a proportional size
$y2 = $m * $x_max; // not $x1
Thanks Norbert =)
[#31] info at personalmis dot com [2008-01-07 04:42:00]
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.
[#32] redcore at gmail dot com [2007-08-09 14:50:44]
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.");
}
?>
[#33] laurens dot stoetzel at gmail dot com [2007-08-03 11:18:14]
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 />';
?>
[#34] phpnetUNDERSCOREspam at erif dot org [2007-06-19 00:26:27]
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);
[#35] jens at kulmegies dot de [2006-10-31 06:30:11]
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]...
[#36] John [2006-02-05 23:57:27]
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.
[#37] webmaster at WWW.ELLESSEWEB.NET [2005-10-26 05:10:42]
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:
<?php
header("Content-type: image/jpeg");
makeThumbnail("http://it2.php.net/images/php.gif", 300);
?>
[#38] Mark at Mild Peril [2005-10-13 04:54:57]
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")
[#39] paul at goldenbakery dot nl [2005-08-05 02:02:51]
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.
[#40] Sean [2005-05-30 10:23:08]
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\" />";
?>
[#41] ajreading at classixshop dot com [2005-04-21 01:30:27]
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);
?>
[#42] mail at soylentgreens dot com [2005-03-30 18:37:14]
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);
?>
[#43] Coodiss at w3bbix dot net [2005-03-15 21:51:54]
Heres a easy way to scale images to the <td> that they are in
*this is broken up so anyone can understand it :)
<?php
$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;
?>
[#44] php dot net at dannysauer dot com [2005-02-12 08:23:17]
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...
[#45] sixzero4 at hotmail dot com [2004-11-29 20:33:07]
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.
[#46] Joshua [2004-08-16 12:26:03]
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.
[#47] cstdenis at hotmail dot com [2004-08-11 11:42:07]
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.
[#48] diablx at hotmail dot com [2004-05-25 14:36:30]
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?php
// 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>
<?php
// 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>
[#49] MagicalTux at FF.st [2004-03-31 03:35:06]
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? )
[#50] MarioPro [2004-03-10 18:13:07]
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! ;)
[#51] yohami dot com - zerodj at hotmail dot com [2004-01-14 07:11:12]
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!
[#52] php (at) thejpster org uk [2003-12-01 18:39:28]
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";
}
[#53] djwishbone at hotmail dot com [2003-11-18 18:31:15]
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
[#54] janoma_cl [2003-10-09 15:19:54]
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>
[#55] simms [2003-09-03 09:47:09]
here's a nice way of resizing user-uploaded files on the fly, using ImageMagick (on linux), but no GD:
<?php
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.
[#56] ten tod xmg ta rotanimrev (reverse it) [2003-09-01 10:30:06]
An additional note to "tightcode_nosp@m_hotmail":
If that doesn't work try this instead:
<?php
$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:
<?php
$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.
[#57] justin at webtekconcepts dot com [2003-08-15 13:27:31]
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.
[#58] webmaster AT theparadox DOT org [2003-05-30 17:16:44]
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;
}
[#59] robertks at hotmail dot com [2003-03-05 09:12:28]
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.
[#60] mogster at boomdesign dot no [2002-03-09 10:58:55]
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