Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Image Functions : imagecopyresized

imagecopyresized

Copy and resize part of an image (PHP 4, PHP 5)
bool imagecopyresized ( resource 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 )

Example 998. 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 above example will output something similar to:

The image will be output at half size, though better quality could be obtained using imagecopyresampled().


Code Examples / Notes » imagecopyresized

hodgman

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]]


saurabh

URGENT!
I am trying to make thumbnails of image(png, jpg, gif)...
Not a single code is working. Do we have to make any changes in php.ini?
which version of gd is required can anybody xplain me whole thing.


del

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);
?>


marcy dot xxx

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);
?>


mecdesign

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).
<?
  // 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);
}
?>


feip

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);
}
}
}
}
?>


halit yesil mail

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
/**
* Author : Halit YESIL
* www : www.halityesil.com, www.prografik.net, www.trteknik.net
* email : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
* GSM : +90.535 648 3504
* Create Date : 21 / 03 / 2007
*
*
* Script : Image resize and croping class.
* You can Write copyright text and attach your logo write on image with this class
*
*
* $obj = new pg_image($arg);
*
*
* Varibles Information
* [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
* [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
* [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
* [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
* [4] width => (integer) => Target File Width
* [5] height => (integer) => Target File Height
* [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
* [7] action => (crop | resize) => Target Action "resize" OR "crop"
* [8] bordersize => (integer 0-5) => Target Border Size
* [9] bordercolor => (color hex) => Target Border Color
* [10] bgcolor => (color hex) => Target Background Color
* [11] copytext => (String) => Copyright Content Text
* [12] copycolor => (color hex) => Copyright Text Color
* [13] copyshadow => (color hex) => Copyright Text Shadow color
* [14] copybgcolor => (color hex) => Copyright Background Color
* [15] copybgshadow => (color hex) => Copyright Background Shadow Color
* [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
* [17] copybordercolor => (color hex) => Copyright Border Color
*   [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
* [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
* [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
*
*
*
*
*/
<?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);
?>


kyle dot florence _

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:
*
*  = creates a resized image based on the max width
*    specified as well as generates a thumbnail from
*    a rectangle cut from the middle of the image.
*
*    @dir   = directory image is stored in
*    @img   = the image name
*    @max_w = the max width of the resized image
*    @max_h = the max height of the resized image
*    @th_w  = the width of the thumbnail
*    @th_h  = the height of the thumbnail
*
**********************************************************/
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.


kyle dot florence

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.
<?
/**********************************************************
* function resizejpeg:
*
*  = creates a resized image based on the max width
*    specified as well as generates a thumbnail from
*    a rectangle cut from the middle of the image.
*
*    @dir    = directory image is stored in
*    @newdir = directory new image will be stored in
*    @img    = the image name
*    @max_w  = the max width of the resized image
*    @max_h  = the max height of the resized image
*    @th_w   = the width of the thumbnail
*    @th_h   = the height of the thumbnail
*
**********************************************************/
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.


malaz

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 "
Image Size: ".$_FILES['imagefile']['size']."";
       echo "
Image Type: ".$_FILES['imagefile']['type']."";
       echo "
Image Copy Done....
";
       }
else {
           echo "
";
           echo "bad file type (".$_FILES['imagefile']['name'].")
";exit;
             }
//-----upload end
//------start thumbnailer
$thumbsize=120;
echo "Thumbnail Info:
1.Thumb defined size: - OK: $thumbsize
";
$imgfile = "../images/$imagefile_name";//processed image
echo "
        2.Image destination: - OK: $imgfile
";
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
echo "3.Image size - OK: W=$width x H=$height
";
$imgratio=$width/$height;
echo "3.Image ratio - OK: $imgratio
";
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
";
$thumb = ImageCreateTrueColor($newwidth,$newheight);
echo "5.TrueColor - OK
";
$source = imagecreatefromjpeg($imgfile);
echo "6.From JPG - OK
";
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK
";
//-----------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.


smelban

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);
}
?>


ob

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.


nils dot clark-bernhard

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


andrvm

One more version of setMemoryForImage (see below)
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!


backglancer

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.
/*
here you can insert any specific "if-else",
or "switch" type of detector of what type of picture this is.
in this example i'll use standard JPG
*/
$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");
?>


robby

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.
/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
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;
}


thomas

Just in addition to the script posted by marcy DOT xxx (AT) gmail.com:
There is one error in this script, that's why it didn't work for me.
Instead of this line:
$source = @function_image_create($imgfile);
use this line:
$source = @$function_image_create($imgfile);


jesse

imagecopyresized() does not do any resampling.  This makes it extremely quick.  If quality is an issue, use imagecopyresampled().

development

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 :-)


finnsi

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

/*

WRITTEN BY:
Finnur Eiriksson, (http://www.centrum.is/finnsi)
Based on snippets that have been posted on www.PHP.net
Drop me an e-mail if you have any questions.

NOTE:
This code is written to either delete or resize pictures in the file system, so if you have your pictures in a database
you will have to make some changes. Also, if you are using other picture formats than .gif's or .jpg's you
will have to add som code as well (Read the comments to find out where to do this).

IMPORTANT:
The $_GET['resizepic'] variable only contains the NAME of the file that is going to be deleted/resized.

The internet guest account (IUSR_SERVERNAME on WINDOWS) must have read and write permissions (execution permission not needed)
in your image directory (i.e. $dir_name = "FooBar"). It is a good idea to have a separate directory for images that users
can upload to and manipulate the contents. Ideally, you should have one directory for the pictures that are used for the website,
and another upload directory

*/

$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');
}
}


?>


skurrilo

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.

fearinc

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.


no

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
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>


06madsenl

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.


brian tyler gmail com

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


konteineris

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
<?
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);
  }
}
?>


heshan

Create thumbnail in GIF format for JPEG and GIF ( with or without transparency, for animated GIF, only the first frame is retained ) originals, thumbnails for PNG images should save in PNG format to support alpha transparency.
For JPEG image and GIF without transparency, simply use imagecopyresized will be OK. For GIF with transparency, we should first understand the behavior of imagecopyresized: it extracts pixels that are not transparent from the specified rectangle area of the source image, resizs the rectangle, probably does some color approximation, then copys to the target image. Suppose that you want to put a picture frame image( only the border is non-transparent ) over a photo( opaque ) to compose a final image, just imagecopyresize the picture frame image to the photo will be OK. To better understand the behavior, consider the case you want to copy several GIF images with transparency together to form a new one, note that the GIF image can only have one transparent color, if the old transparent colors are not dropped by imagecopyresize, it will be confused which color from the originals will be the transparent color in the final image. So imagecopyresize does the right thing. To this point, it is not hard to understand why some people get a black background when they want to create thumbnails for transparent GIF: the original transparent pixels are gone, and the non-transparent pixels are put onto an empty canvas( no color allocated ). Then we arrive
<?php
$im = imagecreatefromgif( 'test.gif' );
// or $im = imagecreatefromjpeg( 'test.jpg' );
$mw = 360; // max width
$mh = 360; // max height
$ow = imagesx( $im );
$oh = imagesy( $im );
if( $ow > $mw || $oh > $mh ) {
   if( $ow > $oh ) {
       $tnw = $mw;
       $tnh = $tnw * $oh / $ow;
   } else {
       $tnh = $mh;
       $tnw = $tnh * $ow / $oh;
   }
} else {
   // although within size restriction, we still do the copy/resize process
   // which can make an animated GIF still
   $tnw = $ow;
   $tnh = $oh;
}
// the document recommends you to use truecolor to get better result
$imtn = imagecreatetruecolor( $tnw, $tnh );
// if the image has transparent color, we first extract the RGB value of it,
// then use this color to fill the thumbnail image as the background. This color
// is safe to be assigned as the new transparent color later on because it will
// be filtered by imagecopyresize.
$originaltransparentcolor = imagecolortransparent( $im );
if(
   $originaltransparentcolor >= 0 // -1 for opaque image
   && $originaltransparentcolor < imagecolorstotal( $im )
   // for animated GIF, imagecolortransparent will return a color index larger
   // than total colors, in this case the image is treated as opaque ( actually
   // it is opaque )
) {
   $transparentcolor = imagecolorsforindex( $im, $originaltransparentcolor );
   $newtransparentcolor = imagecolorallocate(
       $imtn,
       $transparentcolor['red'],
       $transparentcolor['green'],
       $transparentcolor['blue']
   );
   // for true color image, we must fill the background manually
   imagefill( $imtn, 0, 0, $newtransparentcolor );
   // assign the transparent color in the thumbnail image
   imagecolortransparent( $imtn, $newtransparentcolor );
}
// copy/resize as usual
imagecopyresized( $imtn, $im, 0, 0, 0, 0, $tnw, $tnh, $ow, $oh );
imagegif( $imtn, 'test.thumbnail.gif' );
imagedestroy( $im );
imagedestroy( $imtn );
?>
Only do imagecolortransparent( $thumbnail, imagecolortransparent( $source ) ); some times works, just because the color indexes for background transparent pixels in the two images happens to be the same.
PHP5.2.0 with GD bundled (2.0.28 compatible)


nworld3d

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
/**
* Compose a PNG file over a src file.
* If new width/ height are defined, then resize the PNG (and keep all the transparency info)
* Author:  Alex Le - http://www.alexle.net
*/
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 );

/* Noew compose the 2 images */
imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}
/**
* Resize a PNG file with transparency to given dimensions
* and still retain the alpha channel information
* Author:  Alex Le - http://www.alexle.net
*/
function imageResizeAlpha(&$src, $w, $h)
{
/* create a new image with the new width and height */
$temp = imagecreatetruecolor($w, $h);

/* making the new image transparent */
$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

/* Resize the PNG file */
/* use imagecopyresized to gain some performance but loose some quality */
imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
/* use imagecopyresampled if you concern more about the quality */
//imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
return $temp;
}
?>
Example usage:
<?php
header('Content-type: image/png');
/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');
$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);
/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );
/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );
/**
* Open the same PNG file then compose without resizing
* As the original $watermark is passed by reference, it was resized already.
* So we have to reopen it.
*/
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser
ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>


haker4o

<?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);
   }
}
?>


Change Language


Follow Navioo On Twitter
gd_info
getimagesize
image_type_to_extension
image_type_to_mime_type
image2wbmp
imagealphablending
imageantialias
imagearc
imagechar
imagecharup
imagecolorallocate
imagecolorallocatealpha
imagecolorat
imagecolorclosest
imagecolorclosestalpha
imagecolorclosesthwb
imagecolordeallocate
imagecolorexact
imagecolorexactalpha
imagecolormatch
imagecolorresolve
imagecolorresolvealpha
imagecolorset
imagecolorsforindex
imagecolorstotal
imagecolortransparent
imageconvolution
imagecopy
imagecopymerge
imagecopymergegray
imagecopyresampled
imagecopyresized
imagecreate
imagecreatefromgd2
imagecreatefromgd2part
imagecreatefromgd
imagecreatefromgif
imagecreatefromjpeg
imagecreatefrompng
imagecreatefromstring
imagecreatefromwbmp
imagecreatefromxbm
imagecreatefromxpm
imagecreatetruecolor
imagedashedline
imagedestroy
imageellipse
imagefill
imagefilledarc
imagefilledellipse
imagefilledpolygon
imagefilledrectangle
imagefilltoborder
imagefilter
imagefontheight
imagefontwidth
imageftbbox
imagefttext
imagegammacorrect
imagegd2
imagegd
imagegif
imagegrabscreen
imagegrabwindow
imageinterlace
imageistruecolor
imagejpeg
imagelayereffect
imageline
imageloadfont
imagepalettecopy
imagepng
imagepolygon
imagepsbbox
imagepsencodefont
imagepsextendfont
imagepsfreefont
imagepsloadfont
imagepsslantfont
imagepstext
imagerectangle
imagerotate
imagesavealpha
imagesetbrush
imagesetpixel
imagesetstyle
imagesetthickness
imagesettile
imagestring
imagestringup
imagesx
imagesy
imagetruecolortopalette
imagettfbbox
imagettftext
imagetypes
imagewbmp
imagexbm
iptcembed
iptcparse
jpeg2wbmp
png2wbmp
eXTReMe Tracker