search for in the  
<imagecopyresampledimagecreate>
Last updated: Thu, 19 May 2005

imagecopyresized

(PHP 3, PHP 4, PHP 5)

imagecopyresized -- Copy and resize part of an image

Description

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

imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier. If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_image is the same as src_image) but if the regions overlap the results will be unpredictable.

Note: There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by imagecreatetruecolor().

Examples

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 = imagecreate($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().



User Contributed Notes
imagecopyresized
no at name dot com
18-May-2005 06:45
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");
?>
del at kartoon dot net
05-May-2005 03:37
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);
?>
development at lab-9 dot com
25-Apr-2005 05:35
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 :-)
robby at planetargon dot com
28-Feb-2005 09:56
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;
}
haker4o at haker4o dot org
26-Feb-2005 10:57
<?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);
   }
 }
?>
smelban at smwebdesigns dot com
15-Feb-2005 10:37
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);
}
?>
finnsi at centrum dot is
13-Feb-2005 07:30
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');
       }
   }
      
      
?>
thomas at dermueller dot com
10-Feb-2005 03:23
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);
marcy DOT xxx (AT) gmail.com
02-Jan-2005 01:06
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);
?>
backglancer at hotmail
13-Dec-2004 09:10
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");

?>
skurrilo at skurrilo dot de
28-Nov-2000 09:36
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.

<imagecopyresampledimagecreate>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT