there are many snippets here trying to scale an image keeping aspect ratio, I believe every single one is wrong!
I know very often everybody wants to make thumbnails.
this is what I come up with, it's a modified version from what I got from http://asymptomatic.net/2007/05/08/2608/create-thumbnail-in-php
<?
/**
* Creates a resized image from a source image, saves resized image to file
* @param string $src_filename Filename of the image to resize
* @param string $dst_filename Filename of the resized image to output
* @param integer $max_width Maximum width of resized image
* @param integer $max_height Maximum height of resized image
* @return boolean true on success, false on failure
*/
function createthumb($src_filename, $dst_filename, $max_w, $max_h) {
// Get information about the image
list($src_width, $src_height, $type, $attr) = getimagesize($src_filename);
// Load the image based on filetype
switch($type) {
case IMAGETYPE_JPEG:
$src_img = imagecreatefromjpeg($src_filename);
break;
case IMAGETYPE_PNG:
$src_img = imagecreatefrompng($src_filename);
break;
case IMAGETYPE_GIF:
$src_img = imagecreatefromgif($src_filename);
break;
default:
return false;
}
// Did the image fail to load?
if (!$src_img) {
return false;
}
// Calculate the output size based on the original's aspect ratio, this part is PERFECT!
$thumb_w = $max_w;
$thumb_h = $max_h;
$thumb_r = $max_w / $max_h;
$src_r = $src_width / $src_height;
if ($src_r > $thumb_r) {
$thumb_h /= $src_r;
} else if ($src_r < $thumb_r) {
$thumb_w *= $src_r;
}
// Create the output image and copy to source to it
$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
if (($height < 100) || ($width < 100)) {
imagecopyresized($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_width, $src_height);
} else {
imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $src_width, $src_height);
}
/* Sharpen before save?
$sharpenMatrix = array( array(-1, -1, -1), array(-1, 16, -1), array(-1, -1, -1) );
$divisor = 8;
$offset = 0;
imageconvolution( $dst_img, $sharpenMatrix, $divisor, $offset );
//*/
// Get information about the output image
$path_info = pathinfo($dst_filename);
// Setup default return info
$return = true;
// Load the image based on filetype
switch (strtolower($path_info['extension'])) {
case 'jpg':
case 'jpeg':
imagejpeg($dst_img, $dst_filename);
break;
case 'png':
imagepng($dst_img, $dst_filename);
break;
case 'gif':
imagegif($dst_img, $dst_filename);
break;
default:
$return = $false;
}
// Clean up memory
imagedestroy($dst_img);
imagedestroy($src_img);
return $return;
}
?>
getimagesize
(PHP 4, PHP 5)
getimagesize — Ermittelt die Größe einer Grafik
Beschreibung
Die Funktion getimagesize() ermittelt die Dimensionen der
übergebenen Grafik-Datei.
Es werden die Ausmaße in Abhängigkeit vom Grafik-Typ sowie die Höhe und Breite
als ein String zurückgegeben. Dieser kann innerhalb eines
regulären HTML IMG-Tags verwendet werden.
Ausserdem wird der entsprechende HTTP Content-Type
zurückgegeben.
getimagesize() kann im Parameter imageinfo weitere Informationen liefern.
Hinweis: Beachten Sie daß JPC und JP2 aus Komponenten mit verschiedener Farbtiefe bestehen können. In diesem Fall entspricht der Wert für "bits" dem höchsten gefundenen Wert. Des weiteren können JP2-Dateien mehrere JPEG 2000 Codestreams enthalten. In diesem Fall wird getimagesize() Werte entsprechend des ersten gefundenen Codestreams zurückgeben.
Hinweis: Informationen über Icons werden für das Icon mit der höchsten Bitrate ermittelt.
Parameter-Liste
- filename
-
Die zu überprüfende Datei. Dabei kann es sich um eine lokale Datei oder, eine entsprechende Konfiguration vorausgesetzt, um eine entfernte Datei handeln die über einen unterstützen Stream gelesen wird.
- imageinfo
-
Dieser optionale Parameter erlaubt es, erweiterte Informationen aus der Datei zu ermitteln. Momentan werden die verschiedenen JPG APP Markierungen als assoziatives Array zurückgegeben. Diese Markierungen werden von einigen Programmen verwendet um Textinformationen in Grafiken zu speichern. Gebräuchlich ist die Einbettung von IPTC » http://www.iptc.org/ Informationen in die APP13-Markierung. Sie können iptcparse() benutzen, um die binäre APP13-Markierung in ein lesbares Format zu übertragen.
Rückgabewerte
Gibt ein Array mit fünf Elementen zurück.
Index 0 und 1 enthalten Breite respektive Höhe der Grafik.
Hinweis: Einige Formate enthalten keine oder mehrere Grafiken. In diesen Fällen ist getimagesize() möglicherweise nicht in der Lage, die Dimensionen zu ermitteln; der Rückgabewert für Breite und Höhe in ist in diesen Fällen 0.
Index 2 ist eine der IMAGETYPE_XXX-Konstanten entsprechend des Typs der Grafik.
Index 3 ist eine Zeichenkette mit dem Attributen Breite und Höhe in der Form height="yyy" width="xxx" zur Verwendung in einem IMG-Tag.
mime entspricht dem MIME-Type der Grafik. Diese Information kann zur Auslieferung von Grafiken mit dem entsprechenden HTTP Content-type-Header dienen.
Beispiel #1 getimagesize() und MIME-Type
<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
header("Content-type: {$size['mime']}");g
fpassthru($fp);
exit;
} else {
// Fehler
}
?>
channels hat für RGB-Grafiken den Wert 3, für CMYK den Wert 4. bits entspricht der Anzahl der Bits pro Farbe. Allerdings kann diese Angabe für einige Formate irreführend sein. GIF nutzt immer drei Kanäle pro Pixel, aber die Anzahl der Bits pro Pixel kann für ein animiertes GIF mit einer globalen Farbtabelle nicht errechnet werden.
Gibt im Falle eines Fehlers FALSE zurück.
Fehler/Exceptions
Wenn ein Zugriff auf die mit filename angegebene Grafik nicht möglich ist oder es sich um keine valide Grafik handelt wird ein Fehler vom Typ E_WARNING generiert. Bei einem Lesefehler wird ein Fehler vom Typ E_NOTICE erzeugt.
ChangeLog
| Version | Beschreibung |
|---|---|
| 5.3.0 | Unterstützung für Icons |
| 5.2.3 | Lesefehler erzeugen eine E_NOTICE statt einer E_WARNING. |
| 4.3.2 | Unterstützung für JPC, JP2, JPX, JB2, XBM und WBMP wurde hinzugefügt. |
| 4.3.2 | Der Parameter imageinfo unterstützt JPEG2000 |
| 4.3.0 | bits und channels sind auch für andere Grafik-Formate verfügbar |
| 4.3.0 | mime wurde hinzugefügt. |
| 4.3.0 | Unterstützung für SWC wurde hinzugefügt. |
| 4.2.0 | Unterstützung für TIFF wurde hinzugefügt. |
| 4.0.5 | Unterstützung für URLs wurde hinzugefügt. |
Beispiele
Beispiel #2 getimagesize (Datei)
<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>
Beispiel #3 getimagesize (URL)
<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");
// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");
?>
Beispiel #4 getimagesize() gibt IPTC zurück
<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
$iptc = iptcparse($info["APP13"]);
var_dump($iptc);
}
?>
Anmerkungen
Hinweis: Die Funktion getimagesize() benötigt nicht die GD-Bibliothek.
getimagesize
04-Jul-2008 09:31
26-Apr-2008 01:26
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}' />"); }
}
?>
07-Apr-2008 09:14
***********************************
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);
?>
02-Apr-2008 03:17
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 );
}
25-Feb-2008 11: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 ) )
?>
12-Feb-2008 03: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}' />");
}
}
28-Jan-2008 06: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;
11-Jan-2008 12:35
Correction: to find $y2 it should be...
// set y side to a proportional size
$y2 = $m * $x_max; // not $x1
Thanks Norbert =)
07-Jan-2008 01: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.
09-Aug-2007 11: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.");
}
?>
03-Aug-2007 08: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 />';
?>
19-Jun-2007 09: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);
01-Feb-2007 02: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;
}
31-Oct-2006 03: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]...
06-May-2006 12: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;
}
?>
31-Mar-2006 05: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
06-Feb-2006 08: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.
15-Nov-2005 07: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.
26-Oct-2005 02: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);
?>
13-Oct-2005 01: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")
05-Aug-2005 11: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.
30-May-2005 07: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\" />";
?>
30-Apr-2005 01: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);
}
?>
21-Apr-2005 10: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);
?>
31-Mar-2005 04: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);
?>
16-Mar-2005 06: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;
?>
12-Feb-2005 05: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...
30-Nov-2004 05: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'][