©
本文檔使用 php中文網手册 發布
(PHP 4, PHP 5, PHP 7)
imagecopyresized — 拷贝部分图像并调整大小
$dst_image
, resource $src_image
, int $dst_x
, int $dst_y
, int $src_x
, int $src_y
, int $dst_w
, int $dst_h
, int $src_w
, int $src_h
) imagecopyresized()
将一幅图像中的一块正方形区域拷贝到另一个图像中。dst_image
和 src_image
分别是目标图像和源图像的标识符。
In other words, imagecopyresized() will take an
rectangular area from src_image
of width
src_w
and height src_h
at
position (src_x
,src_y
)
and place it in a rectangular area of dst_image
of width dst_w
and height dst_h
at position (dst_x
,dst_y
).
如果源和目标的宽度和高度不同,则会进行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝(如果
dst_image
和 src_image
相同的话)区域,但如果区域交迭的话则结果不可预知。
dst_image
目标图象连接资源。
src_image
源图象连接资源。
dst_x
x-coordinate of destination point.
dst_y
y-coordinate of destination point.
src_x
x-coordinate of source point.
src_y
y-coordinate of source point.
dst_w
Destination width.
dst_h
Destination height.
src_w
源图象的宽度。
src_h
源图象的高度。
成功时返回 TRUE
, 或者在失败时返回 FALSE
。
Example #1 Resizing an image
This example will display the image at half size.
<?php
// File and new size
$filename = 'test.jpg' ;
$percent = 0.5 ;
// Content type
header ( 'Content-Type: image/jpeg' );
// Get new sizes
list( $width , $height ) = getimagesize ( $filename );
$newwidth = $width * $percent ;
$newheight = $height * $percent ;
// Load
$thumb = imagecreatetruecolor ( $newwidth , $newheight );
$source = imagecreatefromjpeg ( $filename );
// Resize
imagecopyresized ( $thumb , $source , 0 , 0 , 0 , 0 , $newwidth , $newheight , $width , $height );
// Output
imagejpeg ( $thumb );
?>
以上例程的输出类似于:
The image will be output at half size, though better quality could be obtained using imagecopyresampled() .
Note:
因为调色板图像限制(255+1 种颜色)有个问题。重采样或过滤图像通常需要多于 255 种颜色,计算新的被重采样的像素及其颜色时采用了一种近似值。对调色板图像尝试分配一个新颜色时,如果失败我们选择了计算结果最接近(理论上)的颜色。这并不总是视觉上最接近的颜色。这可能会产生怪异的结果,例如空白(或者视觉上是空白)的图像。要跳过这个问题,请使用真彩色图像作为目标图像,例如用 imagecreatetruecolor() 创建的。
imagecopyresampled() - 重采样拷贝部分图像并调整大小
[#1] jack at computerrageprevention dot ca [2013-04-19 06:43:06]
There are many user notes here that deal with creating a thumbnail, but I wrote a function that created a thumbnail of an image as it gets uploaded. It is simply a combination of a file uploader with a thumbnail maker, but it is very simple to use now.
Following is an index.php file that contains the upload form, the function, and an example of how to use the function. The last two values in the 'thumb' function are for the width and height limits for the resulting thumbnail. No matter what size the original image, the thumbnail will always fit within the dimensions specified.
<?php
if ($_POST[formname] =="upload")
{
if ($_FILES)
{
foreach ($_FILES as $key => $value)
{
$m = thumb($value, realpath(dirname(__FILE__)) . "/" . "image_1", realpath(dirname(__FILE__)) . "/" . "thumb_1", 150, 150);
// display any messages, whether success or failure
if ($m) { foreach($m as $text) { print "$text<br>"; } }
}
}
}
function thumb($file, $bigname, $thumbname, $maxwidth, $maxheight)
{
if (is_uploaded_file($file[tmp_name]))
{
// determine the image type
if ($file[type] == "image/jpeg") { $ext = ".jpg"; }
if ($file[type] == "image/png") { $ext = ".png"; }
if ($file[type] == "image/gif") { $ext = ".gif"; }
$newfile = $bigname . $ext;
if (move_uploaded_file($file[tmp_name], $newfile))
{
$message[] = "Upload complete";
// get old image size and convert to a maximum width/height combo
$size = getimagesize($newfile);
// only do the conversion if the width is greater than zero, otherwise there could be a division by zero error
if ($size[1] != 0)
{
// Calculate the thumbnail's width an height, based on the max sized allowed and the original's dimensions
if ($size[0]/$size[1] > $maxwidth/$maxheight)
{ $newwidth = $maxwidth; $newheight = floor(($size[1] * $maxwidth) / $size[0]); }
else
{ $newheight = $maxheight; $newwidth = ceil(($size[0] * $maxheight) / $size[1]); }
// Create the thumbnail
$i = imagecreate($newwidth, $newheight);
if ($ext == ".jpg") { $j = imagecreatefromjpeg($newfile); }
if ($ext == ".png") { $j = imagecreatefrompng($newfile); }
if ($ext == ".gif") { $j = imagecreatefromgif($newfile); }
if ($j)
{
// Copy the original image and paste into the new image, resized
if (imagecopyresized($i, $j, 0, 0, 0, 0, $newwidth, $newheight, $size[0], $size[1]))
{
if (imagejpeg($i, $thumbname . $ext, 100))
{
$message[] = "Image thumb created successfully";
} else {
$message[] = "Image thumb would not export";
}
} else {
$message[] = "Image resize failure";
}
} else {
$message[] = "Image type not recognized";
}
} else { // size[1] != 0
$message[] = "Image size invalid";
}
} // move_uploaded_file
} // is_uploaded_file
return $message;
}
print "
<html>
<head>
<title>Image upload and create Thumbnail</title>
</head>
<body>
<form action='index.php' method='POST' enctype='multipart/form-data'>
<input type='hidden' name='formname' value='upload'>
<input type='file' name='fileupload'>
<input type='submit' value='Upload'>
</form>
</body>
</html>
";
?>
NOTE: This does not deal with adjusting palettes or transparent colors, but that can be added if you need it.
[#2] licson0729 at gmail dot com [2011-11-17 03:09:40]
I couldn't find any script that resize an image and give border to it. So I made one myself. Hope that can help you.
<?php
function imagecopyresizedwithborder(&$src,$width,$height,$borderthickess,$bordercolor=NULL)
{
list($width_orig, $height_orig) = array(imagesx($src),imagesy($src));
if ($width && ($width_orig < $height_orig))
{
$width = ($height / $height_orig) * $width_orig;
}
else
{
$height = ($width / $width_orig) * $height_orig;
}
$dst = imagecreatetruecolor($width+2*$borderthickess,$height+2*$borderthickess);
imagecolortransparent($dst,imagecolorallocate($dst,0,0,0));
imagealphablending($dst,false);
imagesavealpha($dst,true);
imagefill($dst,0,0,(isset($bordercolor) ? $bordercolor : imagecolorallocate($dst,255,255,255)));
imagecopyresampled($dst,$src,$borderthickess,$borderthickess,0,0,$width,$height,imagesx($src),imagesy($src));
return $dst;
}
?>
[#3] email at vladislav dot net [2011-06-22 15:30:28]
I didn't find here before any script giving both GIF and PNG transparent images correct, so I offer you mine.
Here is the code for 'image.php' script to generate a resized or original sized images of any type (JPEG, GIF, PNG) with respect to possible transparency of GIF and PNG.
The following script can be used in HTML tag IMG (to display an image marked in database with ID equal to 1 and resized to max 100px) like this:
<img src="image.php?id=1&size=100" />.
<?php
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty($id))
{
$f = ;
$type = ;
}
$imgFunc = '';
switch($type)
{
case 'image/gif':
$img = ImageCreateFromGIF($f);
$imgFunc = 'ImageGIF';
$transparent_index = ImageColorTransparent($img);
if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);
break;
case 'image/jpeg':
$img = ImageCreateFromJPEG($f);
$imgFunc = 'ImageJPEG';
break;
case 'image/png':
$img = ImageCreateFromPNG($f);
ImageAlphaBlending($img,true);
ImageSaveAlpha($img,true);
$imgFunc = 'ImagePNG';
break;
default:
die("ERROR - no image found");
break;
}
header("Content-Type: ".$type);
if(!empty($size))
{
list($w,$h) = GetImageSize($f);
if( $w==0 or $h==0 ) die("ERROR - zero image size");
$percent = $size / (($w>$h)?$w:$h);
if($percent>0 and $percent<1)
{
$nw = intval($w*$percent);
$nh = intval($h*$percent);
$img_resized = ImageCreateTrueColor($nw,$nh);
if($type=='image/png')
{
ImageAlphaBlending($img_resized,false);
ImageSaveAlpha($img_resized,true);
}
if(!empty($transparent_color))
{
$transparent_new = ImageColorAllocate($img_resized,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
$transparent_new_index = ImageColorTransparent($img_resized,$transparent_new);
ImageFill($img_resized, 0,0, $transparent_new_index);
}
if(ImageCopyResized($img_resized,$img, 0,0,0,0, $nw,$nh, $w,$h ))
{
ImageDestroy($img);
$img = $img_resized;
}
}
}
$imgFunc($img);
ImageDestroy($img);
?>
P.S.
The script can be written better (optimized etc.), but I hope you can do it by yourself.
[#4] kvslaap [2009-05-02 07:17:36]
this is a script which loops trough a directory that is currently set to "files" and resizes all images with respecting the image ratio
<?php
//use this line if you get the error message of using too much memory (strip '//')
//ini_set ( "memory_limit", "48M");
$target_width = 800;
$target_height = 600;
if (ob_get_level() == 0) ob_start();
if ($handle = opendir('files/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$destination_path = './files/';
$target_path = $destination_path . basename($file);
$extension = pathinfo($target_path);
$allowed_ext = "jpg, gif, png, bmp, jpeg, JPG";
$extension = $extension[extension];
$allowed_paths = explode(", ", $allowed_ext);
$ok = 0;
for($i = 0; $i < count($allowed_paths); $i++) {
if ($allowed_paths[$i] == "$extension") {
$ok = "1";
}
}
if ($ok == "1") {
if($extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){
$tmp_image=imagecreatefromjpeg($target_path);
}
if($extension == "png") {
$tmp_image=imagecreatefrompng($target_path);
}
if($extension == "gif") {
$tmp_image=imagecreatefromgif($target_path);
}
$width = imagesx($tmp_image);
$height = imagesy($tmp_image);
//calculate the image ratio
$imgratio = ($width / $height);
if ($imgratio>1) {
$new_width = $target_width;
$new_height = ($target_width / $imgratio);
} else {
$new_height = $target_height;
$new_width = ($target_height * $imgratio);
}
$new_image = imagecreatetruecolor($new_width,$new_height);
ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
//Grab new image
imagejpeg($new_image, $target_path);
$image_buffer = ob_get_contents();
ImageDestroy($new_image);
ImageDestroy($tmp_image);
echo " $file resized to $new_width x $new_height <br> \n";
echo str_pad('',4096)."\n";
ob_flush();
flush();
}
}
}
closedir($handle);
echo "Done.";
ob_end_flush();
}
?>
[#5] david from quidware [2009-01-28 00:50:14]
If the script should resize and save thumb I use this simple code, I made a couple corrections from last one and added the possibility to resize to a max HEIGHT:
<?php
function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
{
$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
$gis = getimagesize($tmpname);
$type = $gis[2];
switch($type)
{
case "1": $imorig = imagecreatefromgif($tmpname); break;
case "2": $imorig = imagecreatefromjpeg($tmpname);break;
case "3": $imorig = imagecreatefrompng($tmpname); break;
default: $imorig = imagecreatefromjpeg($tmpname);
}
$x = imagesx($imorig);
$y = imagesy($imorig);
$woh = (!$maxisheight)? $gis[0] : $gis[1] ;
if($woh <= $size)
{
$aw = $x;
$ah = $y;
}
else
{
if(!$maxisheight){
$aw = $size;
$ah = $size * $y / $x;
} else {
$aw = $size * $x / $y;
$ah = $size;
}
}
$im = imagecreatetruecolor($aw,$ah);
if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
if (imagejpeg($im, $save_dir.$save_name))
return true;
else
return false;
}
?>
[#6] it at chmzap dot ru [2008-08-17 22:52:20]
If the script should resize and save thumb I use this simple code:
<?php
function img_resize( $tmpname, $size, $save_dir, $save_name )
{
$save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
$gis = GetImageSize($tmpname);
$type = $gis[2];
switch($type)
{
case "1": $imorig = imagecreatefromgif($tmpname); break;
case "2": $imorig = imagecreatefromjpeg($tmpname);break;
case "3": $imorig = imagecreatefrompng($tmpname); break;
default: $imorig = imagecreatefromjpeg($tmpname);
}
$x = imageSX($imorig);
$y = imageSY($imorig);
if($gis[0] <= $size)
{
$av = $x;
$ah = $y;
}
else
{
$yc = $y*1.3333333;
$d = $x>$yc?$x:$yc;
$c = $d>$size ? $size/$d : $size;
$av = $x*$c; //???????? ????????? ?????????
$ah = $y*$c; //?????? ????????? ?????????
}
$im = imagecreate($av, $ah);
$im = imagecreatetruecolor($av,$ah);
if (imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
if (imagejpeg($im, $save_dir.$save_name))
return true;
else
return false;
}
?>
And now how using this function fast
<?php
if ($_POST[pic])
{
$tmpname = $_FILES['pic']['tmp_name'];
@img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@img_resize( $tmpname , 60 , "../album" , "album_".$id."verysmall.jpg");
}
else
echo "No Images uploaded via POST";
?>
[#7] andrvm at andrvm dot ru [2007-10-14 04:09:35]
One more version of setMemoryForImage (see below)
<?php
function setMemoryForImage($filename)
{
$imageInfo = getimagesize($filename);
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
$memoryLimit = (int) ini_get('memory_limit')*1048576;
if ((memory_get_usage() + $memoryNeeded) > $memoryLimit)
{
ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
return (true);
}
else return(false);
}
?>
//work's it. no problem!
[#8] nils dot clark-bernhard at human-aspects dot de [2007-06-08 04:52:24]
Regarding ob at babcom dot biz's function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)
Make sure to not use a quality of 9 or higher for png resizing.
PHP will output an error like:
fatal libpng error: zlib failed to initialize compressor
or
gd-png error: setjmp returns error condition
[#9] Halit Yesil mail at halityesil dot com [2007-03-23 08:34:16]
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.
Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
<?php
$source = ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
$arg =array( type =>'FILE',
file =>false,
path =>$source,
target =>'',
width =>150,
height =>50,
quality =>80,
action =>'resize',
bordersize =>1,
bordercolor =>'#00CCFF',
bgcolor =>'#000000',
copytext =>'Bodrum 1998',
copycolor =>'#FFFFFF',
//copyshadow =>'#000000',
//copybgcolor =>'#D0FFCC',
//copybgshadow =>'#656565',
copybordersize =>0,
copybordercolor =>'#FFFFFF',
copyposition =>'bottom',
logoposition =>'topleft',
logoimage =>'logo.png');
//$arg = "$source,,400,300,80,resize";
new pg_image($arg);
?>
[#10] feip at feip dot net [2006-11-15 04:23:18]
This code convert images to thumbs.
How he work -
Check source image - Width and Height,
crop a maximum from original image,
resize croped to user defined size
// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);
<?php
function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){
//$src = original image location
//$dst = destination image location
//$dstx = user defined width of image
//$dsty = user defined height of image
$allowedExtensions = 'jpg jpeg gif png';
$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);
for($i=0; count($extensions)>$i; $i=$i+1){
if($extensions[$i]==$currentExtensions)
{ $extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}
if($extensionOK){
$size = getImageSize($src);
$width = $size[0];
$height = $size[1];
if($width >= $dstx AND $height >= $dsty){
$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;
if($proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;
$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
($target['height']*$target['height']))/2);
$crop = round($original['diagonal_center'] - $target['diagonal_center']);
if($proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] = round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}
if($fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif ($fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif ($fileExtension == 'png'){
$from = imageCreateFromPNG($src);
}
$new = ImageCreateTrueColor ($dstx,$dsty);
imagecopyresampled ($new, $from, 0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);
if($fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif ($fileExtension == "gif"){
imagegif($new, $dst);
}elseif ($fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}
?>
[#11] kyle dot florence at gmail dot com [2006-09-15 18:38:55]
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified. This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.
For example, if you have an image that is 800x600 and you specify your new image to be 400x200, it will resize based on the smallest number (in this case 200) and maintain the images 1:1 ratio. So your final image would end up at something like 262x200.
UPDATE: I have updated this function, I added the 'newdir' option in case you want the images saved in a different directory than the script. I also fixed the thumbnail slice so it is perfectly in the center now and fixed the bug that 'ob at babcom dot biz' mentioned so you can safely resize based on width or height now.
<?php
function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
// set destination directory
if (!$newdir) $newdir = $dir;
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image?
if ($or_w > $max_w || $or_h > $max_h) {
// resize by height, then width (height dominant)
if ($max_h < $max_w) {
$rs_h = $max_h;
$rs_w = $rs_h / $ratio;
}
// resize by width, then height (width dominant)
else {
$rs_w = $max_w;
$rs_h = $ratio * $rs_w;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
}
// image requires no resizing
else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $newdir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 2) - ($th_w / 2));
$new_h = (($rs_h / 2) - ($th_h / 2));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $newdir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
?>
Example:
<?php
$dir = './';
$img = 'test.jpg';
resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>
The example would resize the image 'test.jpg' into something 600x400 or less (retains the 1:1 ratio of the image) and creates the file 'thumb_test.jpg' at 300x150.
[#12] nworld3d at yahoo dot com [2006-08-23 17:06:11]
Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image. The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.
The code has been commented to help you read through it. The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.
<?php
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
if( $ovr_w && $ovr_h )
$ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );
imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}
function imageResizeAlpha(&$src, $w, $h)
{
$temp = imagecreatetruecolor($w, $h);
$background = imagecolorallocate($temp, 0, 0, 0);
ImageColorTransparent($temp, $background); // make the new temp image all transparent
imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel
imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
//imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
return $temp;
}
?>
Example usage:
<?php
header('Content-type: image/png');
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');
$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser
ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
[#13] ob at babcom dot biz [2006-08-21 04:32:01]
Regarding the note and function of kyle.florence on August 3rd 2006:
I tried to use his function resizejpeg() for resizing images in my gallery. As far as I can tell it contains a small bug.
Resizing worked fine as long as I had the same maximum width and maximum height specified. Wanting all thumbnails to have the same height - so my images would appear in a straight line on my website both in portrait format and in landscape format - I soon encountered the problem that resizing with different values of maximum width and maximum height would not work proberly.
If you are using the script change the following 2 lines where the resized width and the resized height are calculated:
<?php
$rs_h = $ratio * $max_h;
?>
should be:
<?php
$rs_h = $ratio * $rs_w;
?>
and:
<?php
$rs_w = $max_w / $ratio;
?>
should be:
<?php
$rs_w = $rs_h / $ratio;
?>
The following function is based on Kyle Florence's function. I left out the thumbnail-part and rather added the possibiliy of defining a new dir and new filename for the image. If you need to resize and then create a thumbnail just run the function twice. Here, the thumbnail will contain the full picture and not a cutout of the original image.
The function supports JPG, GIF and PNG resizing. The quality in case of JPG is given to the function as the last parameter $Quality.
The variable names should speak for their usage.
<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
$ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
($TypeCode==3?"png":FALSE)));
$CreateFunction="imagecreatefrom".$ImageType;
$OutputFunction="image".$ImageType;
if ($ImageType) {
$Ratio=($ImageHeight/$ImageWidth);
$ImageSource=$CreateFunction($Dir.$Image);
if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
if ($ImageWidth > $MaxWidth) {
$ResizedWidth=$MaxWidth;
$ResizedHeight=$ResizedWidth*$Ratio;
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
}
if ($ResizedHeight > $MaxHeight) {
$ResizedHeight=$MaxHeight;
$ResizedWidth=$ResizedHeight/$Ratio;
}
$ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
$ResizedHeight,$ImageWidth,$ImageHeight);
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
$ResizedImage=$ImageSource;
}
$OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
return true;
}
else
return false;
}
?>
Before calling the function support for JPG, PNG or GIF should be checked.
[#14] hodgman at ali dot com dot au [2006-08-08 16:37:06]
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.
None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.
However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.
[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
[#15] kyle(dot)florence(_[at]_)gmail(dot)com [2006-08-03 18:43:06]
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.
<?php
function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image
if ($or_w > $max_w || $or_h > $max_h) {
// first resize by width (less than $max_w)
if ($or_w > $max_w) {
$rs_w = $max_w;
$rs_h = $ratio * $max_h;
} else {
$rs_w = $or_w;
$rs_h = $or_h;
}
// then resize by height (less than $max_h)
if ($rs_h > $max_h) {
$rs_w = $max_w / $ratio;
$rs_h = $max_h;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
} else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $dir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 4));
$new_h = (($rs_h / 4));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $dir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
?>
Example:
<?php
$dir = './';
$img = 'test.jpg';
resizejpeg($dir, $img, 600, 600, 300, 150);
?>
The example would resize the image 'test.jpg' into something 600x600 or less (1:1 ratio) and create the file 'thumb_test.jpg' at 300x150.
[#16] 06madsenl at westseneca dot wnyric dot org [2006-04-21 06:05:40]
I was fiddling with this a few days trying to figure out how to resize the original images on my website, but this site:
http://www.sitepoint.com/article/image-resizing-php
Has a great tutorial on using PHP to resize images without creating thumbnails. It was exactly what I was looking to do.
[#17] konteineris at yahoo dot com [2006-02-15 18:42:07]
Function creates a thumbnail from the source image, resizes it so that it fits the desired thumb width and height or fills it grabbing maximum image part and resizing it, and lastly writes it to destination
<?php
function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
list($width, $height) = getimagesize($filename);
$source = imagecreatefromjpeg($filename);
if($width > $th_width || $height > $th_height){
$a = $th_width/$th_height;
$b = $width/$height;
if(($a > $b)^$forcefill)
{
$src_rect_width = $a * $height;
$src_rect_height = $height;
if(!$forcefill)
{
$src_rect_width = $width;
$th_width = $th_height/$height*$width;
}
}
else
{
$src_rect_height = $width/$a;
$src_rect_width = $width;
if(!$forcefill)
{
$src_rect_height = $height;
$th_height = $th_width/$width*$height;
}
}
$src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
$src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);
$thumb = imagecreatetruecolor($th_width, $th_height);
imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);
imagejpeg($thumb,$destination);
}
}
?>
[#18] jesse at method studios [2005-10-04 12:07:43]
imagecopyresized() does not do any resampling. This makes it extremely quick. If quality is an issue, use imagecopyresampled().
[#19] MaLaZ [2005-08-11 19:24:33]
simple script for creating thumbnails with process information and saving original ratio thumbnail to new destination...good then useing with upload or uploaded images:
<?php
//Upload------------------------------------
if(isset( $submit ))
{
if ($_FILES['imagefile']['type'] == "image/jpeg"){
copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
or die ("Could not copy");
echo "";
echo "Image Name: ".$_FILES['imagefile']['name']."";
echo "<br>Image Size: ".$_FILES['imagefile']['size']."";
echo "<br>Image Type: ".$_FILES['imagefile']['type']."";
echo "<br>Image Copy Done....<br>";
}
else {
echo "<br><br>";
echo "bad file type (".$_FILES['imagefile']['name'].")<br>";exit;
}
//-----upload end
//------start thumbnailer
$thumbsize=120;
echo "Thumbnail Info: <br>
1.Thumb defined size: - OK: $thumbsize<br>";
$imgfile = "../images/$imagefile_name";//processed image
echo "
2.Image destination: - OK: $imgfile<br>";
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
echo "3.Image size - OK: W=$width x H=$height<br>";
$imgratio=$width/$height;
echo "3.Image ratio - OK: $imgratio<br>";
if ($imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
echo "4.Thumb new size -OK: W=$newwidth x H=$newheight<br>";
$thumb = ImageCreateTrueColor($newwidth,$newheight);
echo "5.TrueColor - OK<br>";
$source = imagecreatefromjpeg($imgfile);
echo "6.From JPG - OK<br>";
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK<br>";
//-----------end--------------
?>
or without any info, just resizing:
<?php
//------start thumbnailer
$thumbsize=120;
$imgfile = "../images/$imagefile_name";
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = imagecreatefromjpeg($imgfile);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------end--------------
?>
i hope it helps.
[#20] FearINC at gmail dot com [2005-08-10 10:35:06]
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
preg_match("'^(.*)\.(gif|jpe?g|png)$'i", $imageName, $ext);
switch (strtolower($ext[2])) {
case 'jpg' :
case 'jpeg': $im = imagecreatefromjpeg ($imagePath);
break;
case 'gif' : $im = imagecreatefromgif ($imagePath);
break;
case 'png' : $im = imagecreatefrompng ($imagePath);
break;
default : $stop = true;
break;
}
if (!isset($stop)) {
$x = imagesx($im);
$y = imagesy($im);
if (($max_x/$max_y) < ($x/$y)) {
$save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
}
else {
$save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
}
imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);
imagegif($save, "{$saveToDir}{$ext[1]}.gif");
imagedestroy($im);
imagedestroy($save);
}
}
?>
the function for now takes only jpg,gif and png files, but that can easily be changed.
It's an easy to use easy to understand function and I hope it will come useful to someone.
[#21] mecdesign at hotmail dot com [2005-08-07 14:51:48]
This code will resize your images if your image needs to fit (without stretching) into a max height / width destination image that is not a 1:1 ratio (mine was 4:3).
<?php
// Ratios
$image_ratio = $width / $height; // Actual image's ratio
$destination_ratio = $max_width / $max_height; // Ratio of dest. placeholder
// Taller
if($image_ratio < $destination_ratio)
{
//Too tall:
if($height > $max_height)
{
$height = $max_height;
$width = ceil($height / $image_ratio);
}
}
// Wider / balanced & too wide:
else if ($width > $max_width)
{
$width = $max_width;
$height = ceil($width / $image_ratio);
}
?>
[#22] brian <dot> tyler <at> gmail <dot> com [2005-06-12 03:53:23]
I spent last night getting unsuccessful results from this function until I found this note of fluffle <<at>> gmail on the imagecopyresampled page, I have made a slight modification, so you can just cut and paste.
Just to clarify that src_w and src_h do not necessarily need to be the source image width and height, as they specify the size of the rectangle cropped from the source picture, with its top left corner situated at (src_x, src_y).
For example, the code below crops a jpeg image to be square, with the square situated in the centre of the original image, and then resizes it to a 100x100 thumbnail.
function ($image_filename, $thumb_location, $image_thumb_size){
//@$image_filename - the filename of the image you want
//to get a thumbnail for (relative to location of this
//function).
//@$thumb_location - the url (relative to location of this
//function) to save the thumbnail.
//@$image_thumb_size - the x-y dimension of your thumb
//in pixels.
list($ow, $oh) = getimagesize($image_filename);
$image_original = imagecreatefromjpeg($image_filename);
$image_thumb = imagecreatetruecolor($image_thumb_size,$image_thumb_size);
if ($ow > $oh) {
$off_w = ($ow-$oh)/2;
$off_h = 0;
$ow = $oh;
} elseif ($oh > $ow) {
$off_w = 0;
$off_h = ($oh-$ow)/2;
$oh = $ow;
} else {
$off_w = 0;
$off_h = 0;
}
imagecopyresampled($image_thumb, $image_original, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);
imagejpeg($image_thumb, $thumb_location);
}//end function
[#23] no at name dot com [2005-05-18 04:45:15]
I was searching for script, that do not resize on the fly, but copy resized file to other place, so after long searches, i've done this function. I hope it will be usefull for someone:
(This is not original code, i'v taked it from somwhere and edited a ltl :)
<?php
function resize($cur_dir, $cur_file, $newwidth, $output_dir)
{
$dir_name = $cur_dir;
$olddir = getcwd();
$dir = opendir($dir_name);
$filename = $cur_file;
$format='';
if(preg_match("/.jpg/i", "$filename"))
{
$format = 'image/jpeg';
}
if (preg_match("/.gif/i", "$filename"))
{
$format = 'image/gif';
}
if(preg_match("/.png/i", "$filename"))
{
$format = 'image/png';
}
if($format!='')
{
list($width, $height) = getimagesize($filename);
$newheight=$height*$newwidth/$width;
switch($format)
{
case 'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case 'image/gif';
$source = imagecreatefromgif($filename);
break;
case 'image/png':
$source = imagecreatefrompng($filename);
break;
}
$thumb = imagecreatetruecolor($newwidth,$newheight);
imagealphablending($thumb, false);
$source = @imagecreatefromjpeg("$filename");
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
$filename="$output_dir/$filename";
@imagejpeg($thumb, $filename);
}
}
?>
call this function using
<?php
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
[#24] del at kartoon dot net [2005-05-05 01:37:06]
This snippet allows you to grab a thumbnail from the center of a large image. This was used for a client photo gallery for art to give a teaser of the image to come (only a small portion). You could get dynamic with this value. I also put in a scaling factor in case you want to scale down first before chopping.
<?php
// The file
$filename = 'moon.jpg';
$percent = 1.0; // if you want to scale down first
$imagethumbsize = 200; // thumbnail size (area cropped in middle of image)
// Content type
header('Content-type: image/jpeg');
// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;
// Resample
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize); // true color for best quality
$image = imagecreatefromjpeg($filename);
// basically take this line and put in your versin the -($new_width/2) + ($imagethumbsize/2) & -($new_height/2) + ($imagethumbsize/2) for
// the 2/3 position in the 3 and 4 place for imagecopyresampled
// -($new_width/2) + ($imagethumbsize/2)
// AND
// -($new_height/2) + ($imagethumbsize/2)
// are the trick
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);
// Output
imagejpeg($image_p, null, 100);
?>
[#25] development at lab-9 dot com [2005-04-25 15:35:03]
If you read your Imagedata from a Database Blob and use the functions from above to resize the image to a thumbnail improving a lot of traffic, you will have to make temporary copies of the files in order that the functions can access them
Here a example:
// switch through imagetypes
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // overwrite
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // overwrite
// get a temporary filename
// use microtime() to get a unique filename
// if you request more than one file f.e. by creating large numbers of thumbnails, the server could be not fast enough to save all these different files and you get duplicated copies and resizepics() will resize and output often the same content
$filename = microtime()."_temp.".$extension;
// open
$tempfile = fopen($filename, "w+");
// write
fwrite($tempfile, mysql_result($query, 0, 'image'));
// close
fclose($tempfile);
// resize and output the content
echo resizepics($filename, '100', '70');
// delete temporary file
unlink($filename);
NOTE: this script has to be put into a file which sends correct header informations to the browser, otherwise you won't get more to see than a big red cross :-)
[#26] robby at planetargon dot com [2005-02-28 07:56:13]
Most of the examples below don't keep the proportions properly. They keep using if/else for the height/width..and forgetting that you might have a max height AND a max width, not one or the other.
function resizeImage($filename, $max_width, $max_height)
{
list($orig_width, $orig_height) = getimagesize($filename);
$width = $orig_width;
$height = $orig_height;
# taller
if ($height > $max_height) {
$width = ($max_height / $height) * $width;
$height = $max_height;
}
# wider
if ($width > $max_width) {
$height = ($max_width / $width) * $height;
$width = $max_width;
}
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0,
$width, $height, $orig_width, $orig_height);
return $image_p;
}
[#27] haker4o at haker4o dot org [2005-02-26 20:57:20]
<?php
// Resize image.
// Writeen By: Smelban & Haker4o
// Mails smelban@smwebdesigns.com & Haker4o@Haker4o.org
// This code is written to only execute on jpg,gif,png
// $picname = resizepics('pics', 'new widthmax', 'new heightmax');
// Demo $picname = resizepics('stihche.jpg', '180', '140');
$picname = resizepics('picture-name.format', '180', '140');
echo $pickname;
//Error
die( "<font color=\"#FF0066\"><center><b>File not exists :(<b></center></FONT>");
//Funcion resizepics
function resizepics($pics, $newwidth, $newheight){
if(preg_match("/.jpg/i", "$pics")){
header('Content-type: image/jpeg');
}
if (preg_match("/.gif/i", "$pics")){
header('Content-type: image/gif');
}
list($width, $height) = getimagesize($pics);
if($width > $height && $newheight < $height){
$newheight = $height / ($width / $newwidth);
} else if ($width < $height && $newwidth < $width) {
$newwidth = $width / ($height / $newheight);
} else {
$newwidth = $width;
$newheight = $height;
}
if(preg_match("/.jpg/i", "$pics")){
$source = imagecreatefromjpeg($pics);
}
if(preg_match("/.jpeg/i", "$pics")){
$source = imagecreatefromjpeg($pics);
}
if(preg_match("/.jpeg/i", "$pics")){
$source = Imagecreatefromjpeg($pics);
}
if(preg_match("/.png/i", "$pics")){
$source = imagecreatefrompng($pics);
}
if(preg_match("/.gif/i", "$pics")){
$source = imagecreatefromgif($pics);
}
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return imagejpeg($thumb);
if(preg_match("/.jpg/i", "$pics")){
return imagejpeg($thumb);
}
if(preg_match("/.jpeg/i", "$pics")){
return imagejpeg($thumb);
}
if(preg_match("/.jpeg/i", "$pics")){
return imagejpeg($thumb);
}
if(preg_match("/.png/i", "$pics")){
return imagepng($thumb);
}
if(preg_match("/.gif/i", "$pics")){
return imagegif($thumb);
}
}
?>
[#28] smelban at smwebdesigns dot com [2005-02-15 08:37:55]
Resize image proportionaly where you give a max width or max height
<?php
header('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
print $myimage;
function resizeImage($filename, $newwidth, $newheight){
list($width, $height) = getimagesize($filename);
if($width > $height && $newheight < $height){
$newheight = $height / ($width / $newwidth);
} else if ($width < $height && $newwidth < $width) {
$newwidth = $width / ($height / $newheight);
} else {
$newwidth = $width;
$newheight = $height;
}
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return imagejpeg($thumb);
}
?>
[#29] finnsi at centrum dot is [2005-02-13 05:30:37]
If you need to delete or resize images in the filesystem (not in DB) without loosing the image quality...
I commented the code as much as possible so that newbies (like myself) will understand it. ;)
<?php
$dir_name = "FooBar"; // Enter the name of the directory that contains the images
$olddir = getcwd(); // Get the Current Windows Directory to be able to switch back in the end of the script
$dir = opendir($dir_name); //make a directory handle
//To delete a picture
if(isset($_GET['delpic'])){
chdir('images');
$delpic = $_GET['delpic'];
@unlink($delpic);
chdir($olddir);
}
//To resize a picture
if(isset($_GET['resize'])){
//$_GET['resize'] contains the resize-percentage (for example 80 and 40, for 80% and 40% respectively. To double the image in size the user enters 200 etc.)
// File and new size
$percent = ($_GET['resize']/100);
chdir('images');// change the windows directory to the image directory
$filename = $_GET['resizepic'];
// Decide the content type, NB:This code is written to only execute on .gif's and .jpg's
// If you want other formats than .gif's and .jpg's add your code here, in the same manner:
$format='';
if(preg_match("/.jpg/i", "$filename")){
$format = 'image/jpeg';
header('Content-type: image/jpeg');
}
if (preg_match("/.gif/i", "$filename")){
$format = 'image/gif';
header('Content-type: image/gif');
}
if($format!=''){ //This is where the actual resize process begins...
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load the image
switch($format){
case 'image/jpeg':
$source = imagecreatefromjpeg($filename);
break;
case 'image/gif';
$source = imagecreatefromgif($filename);
break;
}
//Get the Image
$thumb = imagecreatetruecolor($newwidth,$newheight);
//This must be set to false in order to be able to overwrite the black
//pixels in the background with transparent pixels. Otherwise the new
//pixels would just be applied on top of the black background.
imagealphablending($thumb, false);
//Make a temporary file handle
$source = @imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//Write the image to the destination file
@imagejpeg($thumb, $filename);
//Change back to the old directory... I'm not sure that this is neccessary
chdir($olddir);
//Specify where you want the user to go after the operation:
header('Location: foobar.php');
}
}
?>
[#30] marcy DOT xxx (AT) gmail.com [2005-01-02 11:06:59]
This example allow to use every kind of image and to resize images with ImageCopyResized(), maintaining proportions..
<?php
// switch to find the correct type of function
$imgfile = 'namefile.jpg';
Header("Content-type: image/".$_GET["type"]);
switch($_GET["type"]){
default:
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
break;
case "jpg":
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
case "jpeg":
$function_image_create = "ImageCreateFromJpeg";
$function_image_new = "ImageJpeg";
break;
case "png":
$function_image_create = "ImageCreateFromPng";
$function_image_new = "ImagePNG";
break;
case "gif":
$function_image_create = "ImageCreateFromGif";
$function_image_new = "ImagePNG";
break;
}
list($width, $height) = getimagesize($imgfile);
// the new weight of the thumb
$newheight = 80;
// Proportion is maintained
$newwidth = (int) (($width*80)/$height);
$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = @function_image_create($imgfile);
ImageCopyResized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
@$function_image_new($thumb);
?>
[#31] backglancer at hotmail [2004-12-13 19:10:44]
Neat script to create a thumbnails no larger than 150 (or user-specific) height AND width.
<?PHP
$picture ="" # picture fileNAME here. not address
$max=150; # maximum size of 1 side of the picture.
$src_img=ImagecreateFromJpeg($picture);
$oh = imagesy($src_img); # original height
$ow = imagesx($src_img); # original width
$new_h = $oh;
$new_w = $ow;
if($oh > $max || $ow > $max){
$r = $oh/$ow;
$new_h = ($oh > $ow) ? $max : $max*$r;
$new_w = $new_h/$r;
}
// note TrueColor does 256 and not.. 8
$dst_img = ImageCreateTrueColor($new_w,$new_h);
ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));
ImageJpeg($dst_img, "th_$picture");
?>
[#32] skurrilo at skurrilo dot de [2000-11-28 07:36:28]
If you aren't happy with the quality of the resized images, just give ImageMagick a try. (http://www.imagemagick.org) This is a commandline tool for converting and viewing images.