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



PHP : Function Reference : Image Functions : imagecopyresampled

imagecopyresampled

Copy and resize part of an image with resampling (PHP 4 >= 4.0.6, PHP 5)
bool imagecopyresampled ( 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 )

imagecopyresampled() copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity.

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.

Parameters

dst_im

Destination image link resource

src_im

Source image link resource

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

Source width

src_h

Source height

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example996.Simple example

This example will resample an image to half its original size.

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// 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($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

The above example will output something similar to:


Example997.Resampling an image proportionally

This example will display an image with the maximum width, or height, of 200 pixels.

<?php
// The file
$filename = 'test.jpg';

// Set a maximum height and width
$width = 200;
$height = 200;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if (
$width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>

The above example will output something similar to:


Notes

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().

Related Examples ( Source code ) » imagecopyresampled


Code Examples / Notes » imagecopyresampled

com.hotmail@backglancer

wrote this for a game I was helping develop:
Auto Tile Maker -- takes the image and cuts it in several smaller pieces, deleting the original... i mean.. this is just for those of you who are lazy, coz the script is simple..
modify at will.
<?
// $newfile is the full address of your newly uploaded file
// $floc = is the location of that file ending with /
// $t is the $_FILES['blah'] of your uploaded file.
// whatever... you guys understand enough to modify this code
$size = getimagesize($newfile);
list($w, $h) = $size;
if ($h > 20 || $w > 20) {
$type = array_pop($size);
switch ($type) {
case 'image/jpeg' : $src_image = imagecreatefromjpeg($newfile); break;
// insert more cases here :) i'm lazy too
default : echo 'not an image!'; return;
}
$i = 0;
for ($y = 0; $y < $h; $y += 20) {
for ($x = 0; $x < $w; $x += 20) {
$i++; // new file names will be like 1monkey.gif 2monkey.gif etc..
$new_image = imagecreatetruecolor(20, 20);
imagecopyresampled ($new_image, $src_image,
0, 0,
$x, $y,
20, 20,
20, 20
);
imagegif($new_image, $floc.$i.$t['name']);
imagedestroy($new_image);
} // x
} // y
unlink($newfile);
}
?>


stemplar444

Two comments regarding imageCopyResampleBicubic() published here.
Quality:
More grainy than imagecopyresampled(). Not very good for bigger destination images, I think.
Speed:
In my tests, it was only faster if destination size was smaller than ~200x200 pixel. The function becomes slower and slower the bigger the destination image gets. In contrast, imagecopyresampled() finished at the same speed, no matter how big the destination was. My source image resoloution ~ 1500x2000 pixel.


blendermf

tim, your resampling gives me better results than the gd function. It looks just as good as what my image resizing software does.

tim dot daldini

Tim's function is a whole lot faster, however, the quality setting doesnt seem right since resizing very big images doesnt affect quality of the resulting thumbnails that much on quality 1 for example.
Anyone has figured out how to use a more correct quality setting by comparing image surfaces (for example) basing on Tim's function?
images with a total of 10Megapixels that contain 5Megapixels when resized should use the same quality setting like images that contain 1Megapixels but only 0.5 when resized.
Not hard to understand, but the memoryload would be a lot lower if the function could decide to use a setting of quality 1 automatically when resizing big images to small thumbnails. This would be handy especially when using the function for images of various sizes in the same application.


eblejr

Tim's code is fast, but if you're trying to put resampled images anywhere but in the top-left corner, it doesn't work.

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


afrowuk

This simple function resizes a JPG image file giving just a maximum width, and resizes keeping the aspect ratio. This is useful if you have to resize a JPG image that must fit the width of i.e. a div element, but doesn't have to have a maximum height.
<?
function resizeJPG($jpgFile, $width) {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($jpgFile);
$height = (int) (($width / $width_orig) * $height_orig);
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($jpgFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output
imagejpeg($image_p, $jpgFile, 100);
}
?>
-Stu


ron

This Bicubic resample algorithm is based on the one Scott posted earlier, only this one is about 50% faster for truecolor images and about 10% faster for palette images.
<?
function imageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
 $scaleX = ($src_w - 1) / $dst_w;
 $scaleY = ($src_h - 1) / $dst_h;
 $scaleX2 = $scaleX / 2.0;
 $scaleY2 = $scaleY / 2.0;
 $tc = imageistruecolor($src_img);
 for ($y = $src_y; $y < $src_y + $dst_h; $y++)
 {
   $sY   = $y * $scaleY;
   $siY  = (int) $sY;
   $siY2 = (int) $sY + $scaleY2;
   for ($x = $src_x; $x < $src_x + $dst_w; $x++)
   {
     $sX   = $x * $scaleX;
     $siX  = (int) $sX;
     $siX2 = (int) $sX + $scaleX2;
     if ($tc)
     {
       $c1 = imagecolorat($src_img, $siX, $siY2);
       $c2 = imagecolorat($src_img, $siX, $siY);
       $c3 = imagecolorat($src_img, $siX2, $siY2);
       $c4 = imagecolorat($src_img, $siX2, $siY);
       $r = (($c1 + $c2 + $c3 + $c4) >> 2) & 0xFF0000;
       $g = ((($c1 & 0xFF00) + ($c2 & 0xFF00) + ($c3 & 0xFF00) + ($c4 & 0xFF00)) >> 2) & 0xFF00;
       $b = ((($c1 & 0xFF)   + ($c2 & 0xFF)   + ($c3 & 0xFF)   + ($c4 & 0xFF))   >> 2);
       imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
     }
     else
     {
       $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
       $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
       $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
       $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));
       $r = ($c1['red']   + $c2['red']   + $c3['red']   + $c4['red']  ) << 14;
       $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
       $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;
       imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
     }
   }
 }
}
?>


kristijan

There is bug in POST from tim at leethost dot com
25-Jan-2007 02:00.
Function work correctly when you making thumb from 0,0 to width/height. But if you want copy resized picture to other coordinates then you must change code in this:
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
if (empty($src_image) || empty($dst_image)) { return false; }
if ($quality <= 1)
{
  $temp = imagecreatetruecolor ($dst_w + 1, $dst_h + 1);
  imagecopyresized ($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h);
  imagecopyresized ($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h);
  imagedestroy ($temp);
}
elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h))
{
  $tmp_w = $dst_w * $quality;
  $tmp_h = $dst_h * $quality;
  $temp = imagecreatetruecolor ($tmp_w + 1, $tmp_h + 1);
  imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h);
  imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h);
  imagedestroy ($temp);
} else
{
  imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
}
return true;
}


dmitry

Simple script on change of width and automatic creation of height, and also creation of the signature in the right we string to a corner. (Only for Jpg)
function easyResize($img_sourse, $save_to, $quality, $width, $str) {
$size = GetImageSize($img_sourse);
$im_in = ImageCreateFromJPEG($img_sourse);

$new_height = ($width * $size[1]) / $size[0]; // Generate new height for image
$im_out = imagecreatetruecolor($width, $new_height);

ImageCopyResampled($im_out, $im_in, 0, 0, 0, 0, $width, $new_height, $size[0], $size[1]);

#Find X & Y for note
$X_var = ImageSX($im_out);
$X_var = $X_var - 130;
$Y_var = ImageSY($im_out);
$Y_var = $Y_var - 25;
#Color
$white = ImageColorAllocate($im_out, 0, 0, 0);

#Add note(simple: site address)
ImageString($im_out,2,$X_var,$Y_var,$str,$white);
ImageJPEG($im_out, $save_to, $quality); // Create image
ImageDestroy($im_in);
ImageDestroy($im_out);
}
// $str -  Inscription on the image;


caio

Ok guys, the ultimate image merging tool, enjoy:
 function watermark($sourcefile, $watermarkfiles, $destination, $quality=90) {
 /*
 
   $sourcefile = Filename of the picture to be watermarked.
   $watermarkfile = files to add. Each is: array ( 'filename' => filename , 'position' => position to show(array), 'resample' => new dimension(array) )
      You can omit any except filename
   $destination = jpg or png file to output (jpg if source is jpg, png if source is png). Send blank to direct output  
   Sample:
 
   $batch = array ( array ( 'filename' => "watermark.png",
                            'position' => array(100,0),
                          ),
                   array ( 'filename' => "brilho.png",
                           'position' => array(200,200),
                           'resample' => array(30,30)
                          )
                  );
   watermark("picture.jpg", $batch, "", 90); <--  will add both images in bath on top of picture, preserving transparency
 
 */
 
 $ih = getimagesize($sourcefile);
 $ispng = $ih[2] == 3;
 if ($ispng)
   $sourcefile_id = imagecreatefrompng($sourcefile);
 else
   $sourcefile_id = imagecreatefromjpeg($sourcefile);
 
 $sourcefile_width=imageSX($sourcefile_id);
 $sourcefile_height=imageSY($sourcefile_id);  
 
 foreach ($watermarkfiles as $x => $watermarkfile) {
   $watermarkfile_id = imagecreatefrompng($watermarkfile['filename']);
   imageAlphaBlending($watermarkfile_id, false);
   imageSaveAlpha($watermarkfile_id, true);    
   $watermarkfile_width=imageSX($watermarkfile_id);
   $watermarkfile_height=imageSY($watermarkfile_id);
   
   // resample?
   if (isset($watermarkfile['resample'])) {
     $im_dest = imagecreatetruecolor ($watermarkfile['resample'][0], $watermarkfile['resample'][1]);
     imagealphablending($im_dest, false);
     imagecopyresampled($im_dest, $watermarkfile_id, 0, 0, 0, 0, $watermarkfile['resample'][0], $watermarkfile['resample'][1], $watermarkfile_width, $watermarkfile_height);
     imagesavealpha($im_dest, true);
     imagedestroy($watermarkfile_id);
     $watermarkfile_id = $im_dest;
     $watermarkfile_width = $watermarkfile['resample'][0];
     $watermarkfile_height = $watermarkfile['resample'][1];
   }
   
   // position ? if none given, centered
   if (isset($watermarkfile['position']))
     list($dest_x,$dest_y) = $watermarkfile['position'];
   else {
     $dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 ); // centered
     $dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 ); // centered
   }
   
   imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height);
   imagedestroy($watermarkfile_id);
 }
 if ($ispng)
   imagepng($sourcefile_id,$destination);
 else
   imagejpeg($sourcefile_id,$destination,$quality);
 imagedestroy($sourcefile_id);
}


fluffle gmail com

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.
list($ow, $oh) = getimagesize($image_filename);
$big = imagecreatefromjpeg($image_filename);
$thumb = imagecreatetruecolor(100,100);
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($thumb, $big, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);


05-jul-2005 01:46

It should be noted that the imagecopyresampled() function is much more blurry than Photoshop CS's default bicubic funtion. And looks similar to a blury version of Photoshop's bilinear function. The documentation fails to note which algorithm is used in resampling.

16-jul-2004 01:09

In add to all the posts that describes how to create thumbnails:
If you are trying to resample a png image with its transparency you need to do this workaround:
<?
...
         $t_im = imageCreateTrueColor($t_wd,$t_ht);
         imageAntiAlias($t_im,true);
         imagealphablending($t_im, false);
         imagesavealpha($t_im,true);
         $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 0);
         for($x=0;$x<$t_wd;$x++) {
           for($y=0;$y<$t_ht;$y++) {
             imageSetPixel( $t_im, $x, $y, $transparent );
           }
         }
         imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
         imagePNG($t_im, $image_name);
...
?>
The alphablending must be off so the imagesavealpha can be true.
The double FORs is need to fix the problem with imagefill function that not support colors with alpha setted.
It is TO SLOWLIER than imagefill, but do a nice work with static images.
Take a look and enjoy the nice result.
(this workaround needs the gd2 library)
[s]
Pigmeu


pike-php

If you have a bug that imagecopyresampled is completely ignoring srcX and srcY (a known and closed bug - http://bugs.php.net/bug.php?id=12780)  you can ofcourse apply two operations to do the same. E.g., instead of saying
ImageCopyResampled($dst_img, $src_img, 0, 0, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
you can say
ImageCopyResampled($tmp_img, $src_img, -$srcX, -$srcY, "BUG","BUG", $orgW, $orgH, $orgW, $orgH);
ImageCopyResampled($dst_img, $tmp_img, 0, 0, "BUG","BUG", $dstW, $dstH, $srcW, $srcH);
which has the same effect but is twice as slow and blurry. you may replace "BUG","BUG" with anything you like without sideeffects :)
$2c,
*pike


nicolas dot grasset

If you are looking for a function that can resample your photos to a given size, no matter its original size and/or ratio, here it is. And to make more fun (beacause life has to be fun), you can even chose a border size for the picture!
$position can either be topleft, topright, bottomleft, bottomright or center.
<?php
function imagecopyresampledselection($filename, $desired_width, $desired_height, $bordersize, $position)
{
// Get new dimensions
list($width, $height) = getimagesize($filename);
if($desired_width/$desired_height > $width/$height):
$new_width = $desired_width;
$new_height = $height * ($desired_width / $width);
else:
$new_width = $width * ($desired_height / $height);
$new_height = $desired_height;
endif;

// Resize
$image_p = imagecreatetruecolor($new_width, $new_height);
$image_f = imagecreatetruecolor($desired_width, $desired_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Adjust position
switch($position)
{
case("topleft"):
$x = $bordersize;
$y = $bordersize;
break;

case("topright"):
$x = $new_width - $desired_width + $bordersize;
$y = $bordersize;
break;

case("bottomleft"):
$x = $bordersize;
$y = $new_height - $desired_height + $bordersize;
break;

case("bottomright"):
$x = $new_width - $desired_width + $bordersize;
$y = $new_height - $desired_height + $bordersize;
break;

case("center"):
$x = ($new_width - $desired_width) / 2 + $bordersize;
$y = ($new_height - $desired_height) / 2 + $bordersize;
break;
}

// Resample with 1px border
imagecopyresampled($image_f, $image_p, $bordersize, $bordersize, $x, $y, $desired_width - 2 * $bordersize,
$desired_height - 2 * $bordersize,
$desired_width - 2 * $bordersize,
$desired_height - 2 * $bordersize);

return $image_f;
}
$image_f = imagecopyresampledselection('test.jpg', 571, 319, 1, "center");
header('Content-type: image/jpeg');
imagejpeg($image_f, null, 100);
?>
To see a result, just browse http://www.notup2u.net/v8
Nicolas Grasset


erik

I've changed the script from info at lontronics dot nl a little bit so the thumbnail is not cutted off when this is not necessary.
<?php
// Resize function
// $pictype is optional. When empty the image will not be cutted off
function resize($filename, $dest, $width, $height, $pictype = "")
{
 $format = strtolower(substr(strrchr($filename,"."),1));
 switch($format)
 {
   case 'gif' :
   $type ="gif";
   $img = imagecreatefromgif($filename);
   break;
   case 'png' :
   $type ="png";
   $img = imagecreatefrompng($filename);
   break;
   case 'jpg' :
   $type ="jpg";
   $img = imagecreatefromjpeg($filename);
   break;
   case 'jpeg' :
   $type ="jpg";
   $img = imagecreatefromjpeg($filename);
   break;
   default :
   die ("ERROR; UNSUPPORTED IMAGE TYPE");
   break;
 }
 list($org_width, $org_height) = getimagesize($filename);
 $xoffset = 0;
 $yoffset = 0;
 if ($pictype == "thumb") // To minimize destortion
 {
   if ($org_width / $width > $org_height/ $height)
   {
     $xtmp = $org_width;
     $xratio = 1-((($org_width/$org_height)-($width/$height))/2);
     $org_width = $org_width * $xratio;
     $xoffset = ($xtmp - $org_width)/2;
   }
   elseif ($org_height/ $height > $org_width / $width)
   {
     $ytmp = $org_height;
     $yratio = 1-((($width/$height)-($org_width/$org_height))/2);
     $org_height = $org_height * $yratio;
     $yoffset = ($ytmp - $org_height)/2;
   }
 //Added this else part -------------
 } else {    
     $xtmp = $org_width/$width;
     $new_width = $width;
     $new_height = $org_height/$xtmp;
     if ($new_height > $height){
       $ytmp = $org_height/$height;
       $new_height = $height;
       $new_width = $org_width/$ytmp;
     }
     $width = round($new_width);
     $height = round($new_height);
 }
 
 $img_n=imagecreatetruecolor ($width, $height);
 imagecopyresampled($img_n, $img, 0, 0, $xoffset, $yoffset, $width, $height, $org_width, $org_height);
 if($type=="gif")
 {
   imagegif($img_n, $dest);
 }
 elseif($type=="jpg")
 {
   imagejpeg($img_n, $dest);
 }
 elseif($type=="png")
 {
   imagepng($img_n, $dest);
 }
 elseif($type=="bmp")
 {
   imagewbmp($img_n, $dest);
 }
 Return true;
}
?>


carnivorous_winds_fr

I tried this code from a previous post.
<?
...
        $t_im = imageCreateTrueColor($t_wd,$t_ht);
        imageAntiAlias($t_im,true);
        imagealphablending($t_im, false);
        imagesavealpha($t_im,true);
        $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 0);
        for($x=0;$x<$t_wd;$x++) {
          for($y=0;$y<$t_ht;$y++) {
            imageSetPixel( $t_im, $x, $y, $transparent );
          }
        }
        imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
        imagePNG($t_im, $image_name);
...
?>
It seems that it is not working correctly. In my test the source picture in ImageCopyResampled() is smaller than the destination picture $t_im, the remaining part is white !
I changed transparent alpha channel to 127, and I tried to replace loops with imagefilledrectangle().
It works fine and these resource greedy loops are removed.
Here is the code with my change.
<?
...
        $t_im = imageCreateTrueColor($t_wd,$t_ht);
        imageAntiAlias($t_im,true);
        imagealphablending($t_im, false);
        imagesavealpha($t_im,true);
        $transparent = imagecolorallocatealpha($t_im, 255, 255, 255, 127);
        imagefilledrectangle($t_img, 0, 0, $t_wd, $t_ht, $transparent);
        imageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $t_wd, $t_ht, $o_wd, $o_ht);
        imagePNG($t_im, $image_name);
...
?>


tim

Here's an improved and corrected version of my fastimagecopyresampled script.  Because I typically scale entire images it appears my previous code was not properly tested.  In any case, this new script has been thoroughly tested, cleaned up, and enhanced.  The code is a little tighter and quality values between 0 and 1 will yield a mosaic effect (basically lowering quality below the pervious lowest value of 1).  I would still suggest using a quality of 2 to 4 as that's the primary purpose of this script, which is high quality and fast results.  Don't be afraid of using a quality value of 1.5 for extreme cases where you have a bunch of very large images from digital cameras (like those 10M pixel cameras theses days) and creating thumbnails in batch mode.  Even a quality of 1.5 is a big improvement over imagecopyresized and is ultra-fast.
Anyway, enjoy and I hope this is the bug-free last version.
<?
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
 // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.
 // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled".
 // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.
 // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.
 //
 // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.
 // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.
 // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.
 // 2 = Up to 95 times faster.  Images appear a little sharp, some prefer this over a quality of 3.
 // 3 = Up to 60 times faster.  Will give high quality smooth results very close to imagecopyresampled, just faster.
 // 4 = Up to 25 times faster.  Almost identical to imagecopyresampled for most images.
 // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.
 if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }
 if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {
   $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);
   imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);
   imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);
   imagedestroy ($temp);
 } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
 return true;
}
?>


djneoform

Here's a function i made that will force a given set of constraints on an image (usrfull if you want to make thumbnails that are all the same size) while keeping aspect ratio.
It resizes, then crops the extra off the top or bottom.
function forceConstraints($srcFile, $srcType, $dstType, $dstWidth, $dstHeight, $dstPath)
{
if ($srcType == "image/jpeg")
$handle = @imagecreatefromjpeg($srcFile);
else if ($srcType == "image/png")
$handle = @imagecreatefrompng($srcFile);
else if ($srcType == "image/gif")
$handle = @imagecreatefromgif($srcFile);
else
return false;
if (!$handle)
return false;
$srcWidth  = @imagesx($handle);
$srcHeight = @imagesy($handle);
if ($srcWidth >= $dstWidth && $srcHeight >= $dstHeight)
{
$newHandle = @imagecreatetruecolor($dstWidth, $dstHeight);
if (!$newHandle)
return false;
if($srcHeight < $srcWidth)
{
$ratio = (double)($srcHeight / $dstHeight);
$cpyWidth = round($dstWidth * $ratio);
if ($cpyWidth > $srcWidth)
{
$ratio = (double)($srcWidth / $dstWidth);
$cpyWidth = $srcWidth;
$cpyHeight = round($dstHeight * $ratio);
$xOffset = 0;
$yOffset = round(($srcHeight - $cpyHeight) / 2);
} else {
$cpyHeight = $srcHeight;
$xOffset = round(($srcWidth - $cpyWidth) / 2);
$yOffset = 0;
}
} else {
$ratio = (double)($srcWidth / $dstWidth);
$cpyHeight = round($dstHeight * $ratio);
if ($cpyHeight > $srcHeight)
{
$ratio = (double)($srcHeight / $dstHeight);
$cpyHeight = $srcHeight;
$cpyWidth = round($dstWidth * $ratio);
$xOffset = round(($srcWidth - $cpyWidth) / 2);
$yOffset = 0;
} else {
$cpyWidth = $srcWidth;
$xOffset = 0;
$yOffset = round(($srcHeight - $cpyHeight) / 2);
}
}
if (!@imagecopyresampled($newHandle, $handle, 0, 0, $xOffset, $yOffset, $dstWidth, $dstHeight, $cpyWidth, $cpyHeight))
return false;
@imagedestroy($handle);
if ($dstType == "png")
@imagepng($newHandle, $dstPath.".png");
else if ($dstType == "jpg")
@imagejpeg($newHandle, $dstPath.".jpg", 90);
else if ($dstType == "gif")
@imagegif($newHandle, $dstPath.".gif");
else
return false;
@imagedestroy($newHandle);
return true;
} else {
return "Sorry, that image is too small. The image must be at least ".$dstWidth."x".$dstHeight." pixels in size.";
}
}


12-aug-2005 01:19

Here is my own custom utility which I call "Thumbnailer" (I know it is cheesy).
It's rather short, and it will take JPEG (you can change that easily), and
format it to a specified output width and height as a PNG
(or whatever else you choose):
<?php
//Dimensions
$outWidth=100; $outHeight=75;
//Do it
$imgSrc=imagecreatefromjpeg("[source]");
$srcWidth=imagesx($imgSrc);
$srcHeight=imagesy($imgSrc);
//Make thumbnails
$imgOut=imagecreatetruecolor($outWidth,$outHeight);
imagerectangle($imgOut,0,0,$outWidth,$outHeight,
imagecolorallocate($imgOut,0,0,0));
//Copy them proportionatly
$dx=0; $dy=0; $dw=$outWidth; $dh=$outHeight;
if ($outWidth*$srcHeight!=$outHeight*$srcWidth) { //Non-proportional, cut-off
//Which dimensions is larger
if ($srcWidth>$srcHeight) { //Empty space on top and bottom
 $dw=$outWidth;
 $dh=($dw*$srcHeight)/$srcWidth;
 $dy=($outHeight-$dh)/2;
}
else { //Empty space on left and right
 $dh=$outHeight;
 $dw=($dh*$srcWidth)/$srcHeight;
 $dx=($outWidth-$dw)/2;
}
}
imagecopyresampled($imgOut,$imgSrc,$dx,$dy,0,0,
$dw,$dh,$srcWidth,$srcHeight); //imagecopyresized for lower quality
//Create the thumbnail and destroy everything else
imagepng($imgOut,"[out]");
echo "Image created successfully: $outWidth x $outHeight, ".round(filesize("[source]")/1024)." KB
";
imagedestroy($imgSrc);
imagedestroy($imgOut);
?>
I just use this as a loop to create thumbnails for a series of ordered images.


mracek

Here is function which:
- resize and crop (crop format 4:3 or 1:1)
- methode resample/resize
- open jpg, gif, bmp, png
- save jpg (85%), gif, bmp, png
- show images
$FILE_MIMES = array(
'image/pjpeg'=>"jpg",
'image/jpeg'=>"jpg",
'image/jpg'=>"jpg",
'image/png'=>"png",
'image/x-png'=>"png",
'image/gif'=>"gif",
'image/bmp'=>"bmp");
$FILE_EXTS  = array('.jpeg','.jpg','.png','.gif','.bmp');
$MAX_SIZE  = 16777216;
$lng=array(
's_imgDimension'=>array(
      "80",
      "320"
      ),
's_imgCrop'    =>array(
      "- auto -",
      "na sirku",
      "na vysku",
      "ctverec",
      "- zadne -"
      ),
's_imgFormat'    =>array(
      "4/3",
      "1/1"
      ),
's_imgType'    =>array(
      "jpg",
      "png",
      "gif",
      "bmp"
      ),
's_imgMethode'    =>array(
      "resample",
      "resize"
      )
);
function PPimageTransform($photo1,$type1,$dim,$crop,
$format,$methode,$photo2,$type2)
{
if ($photo1!=="" && File_Exists($photo1))
{
  if (!($crop>0 && $crop<5)) $crop=0;
  width=x"
  list($w,$h) = GetImageSize($photo1);
  $w=($w<1)?1:$w;
  $h=($h<1)?1:$h;
  $wh=$w/$h;
  // format
  $format=($format=='4/3')?4/3:1;
  // auto crop
  if ($crop==0)
      {
      $z1=$format-  ($format-1)/2;
      $z2=$format+(1-$format-1)/2;
          if ($wh>$z1) {$crop=1;}
      elseif ($wh<$z2) {$crop=2;}
      else        {$crop=3;}
      }
  // scale
  if ($crop==4)
      {
      $a=$w>$h?$w:$h;
      $scale=$dim/$a;
      $nw=$w*$scale;$nw=($nw<1)?1:$nw;
      $nh=$h*$scale;$nh=($nh<1)?1:$nh;
      $d=array(0,0,floor($nw),floor($nh));
      $s=array(0,0,$w,$h);
      }
  else
      {
          if ($crop==3) {$nw=1;$nh=1;}
      elseif ($crop==2) {$nw=1/$format;$nh=1;}
      elseif ($crop==1) {$nw=1;$nh=1/$format;}
      $nw*=$dim;$nw=($nw<1)?1:$nw;
      $nh*=$dim;$nh=($nh<1)?1:$nh;
 
      $s1=$nw/$w;
      $s2=$nh/$h;
      $h1=$nh*$s1;
      $w2=$nw*$s2;
      $s1=($h1<=$nh)?$s1:0;
      $s2=($w2<=$nw)?$s2:0;
      $scale=($s1>$s2)?$s1:$s2;
      $scale=($scale<=0)?1:$scale;
      $d=array(0,0,floor($nw),floor($nh));
      $x1=floor(($w-$d[2]/$scale)/2);$x1=$x1<0?0:$x1;
      $y1=floor(($h-$d[3]/$scale)/2);$y1=$y1<0?0:$y1;
      $s=array($x1,$y1,floor($w-2*$x1),floor($h-2*$y1));
      }
  // input/output
  switch($type1)
      {
      case 'jpg': $imgIn = ImageCreateFromJPEG; break;
      case 'png': $imgIn = ImageCreateFromPNG;  break;
      case 'gif': $imgIn = ImageCreateFromGIF;  break;
      case 'bmp': $imgIn = ImageCreateFromWBMP; break;
      default: return FALSE; break;
      }
  switch($type2)
      {
      case 'jpg': $imgOut = ImageJPEG; break;
      case 'png': $imgOut = ImagePNG;  break;
      case 'gif': $imgOut = ImageGIF;  break;
      case 'bmp': $imgOut = ImageWBMP; break;
      default: return FALSE; break;
      }
  // resample (d-destination, s-source)
  $image1 = $imgIn($photo1);
  if ($methode==0)
      {
      $image2 = ImageCreateTruecolor($d[2],$d[3]);
      ImageCopyResampled($image2, $image1,
$d[0],$d[1], $s[0],$s[1], $d[2],$d[3], $s[2],$s[3]);
      }
  else    {
      $image2 = ImageCreate($d[2],$d[3]);
      ImageCopyResized($image2, $image1,
$d[0],$d[1], $s[0],$s[1], $d[2],$d[3], $s[2],$s[3]);
      }
  // output
  if ($type2=='jpg')
      {$imgOut($image2,$photo2,85);}
  else    {$imgOut($image2,$photo2);}
  ImageDestroy($image2);
  ImageDestroy($image1);
  }
}


madfancier

Hello,
If you're looking for a function that can actually do all kinds of image resizing, support png, gif, jpeg, be agnostic to resize directions (upscaling and downscaling), support proportionality and absence of it, support one-dimension constraints (width or height), and preserve transparency, don't look any further. : )
Warning - this function replaces the passed-in file with the resized file with the same name and format.  Modify as necessary.
You can find more information about this function's usage and features in this article on my blog:
http://www.mediumexposure.com/node/19
<?php
/*
* Written by Maxim Chernyak (mx_)
*
* Please visit http://www.mediumexposure.com for more PHP stuff.
* If you have any criticism, suggestions, improvements, or you simply liked the function, I would appreciate if you dropped me a note on my blog (mentioned above).
*
* Feel free to use anywhere, anyhow. : )
*
*/
function smart_resize_image( $file, $width = 0, $height = 0, $proportional = false, $use_linux_command = false )
   {
       if ( $height <= 0 && $width <= 0 ) {
           return false;
       }
     
       $info = getimagesize($file);
       $image = '';
     
       $final_width = 0;
       $final_height = 0;
       list($width_old, $height_old) = $info;
     
       if ($proportional) {
         
           $proportion = $width_old / $height_old;
         
           if ( $width > $height && $height != 0) {
               $final_height = $height;
               $final_width = $final_height * $proportion;
           }
           elseif ( $width < $height && $width != 0) {
               $final_width = $width;
               $final_height = $final_width / $proportion;
           }
           elseif ( $width == 0 ) {
               $final_height = $height;
               $final_width = $final_height * $proportion;          
           }
           elseif ( $height == 0) {
               $final_width = $width;
               $final_height = $final_width / $proportion;          
           }
           else {
               $final_width = $width;
               $final_height = $height;
           }
       }
       else {
           $final_width = ( $width <= 0 ) ? $width_old : $width;
           $final_height = ( $height <= 0 ) ? $height_old : $height;
       }
 
       switch ( $info[2] ) {
           case IMAGETYPE_GIF:
               $image = imagecreatefromgif($file);
           break;
           case IMAGETYPE_JPEG:
               $image = imagecreatefromjpeg($file);
           break;
           case IMAGETYPE_PNG:
               $image = imagecreatefrompng($file);
           break;
           default:
               return false;
       }
     
       $image_resized = imagecreatetruecolor( $final_width, $final_height );
       imagecolortransparent($image_resized, imagecolorallocate($image_resized, 0, 0, 0) );
       imagealphablending($image_resized, false);
       imagesavealpha($image_resized, true);
     
       imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);
     
       if ( $use_linux_command )
           exec('rm '.$file);
       else
           @unlink($file);
     
       switch ( $info[2] ) {
           case IMAGETYPE_GIF:
               imagegif($image_resized, $file);
           break;
           case IMAGETYPE_JPEG:
               imagejpeg($image_resized, $file);
           break;
           case IMAGETYPE_PNG:
               imagepng($image_resized, $file);
           break;
           default:
               return false;
       }
     
       return true;
   }
?>


m.kumar

For those who think that resampling loads the server too badly, have a look at this fine article over at zend:
http://www.zend.com/zend/art/scriptcaching.php
it describes how to create static html from scripts, however, this technique is pretty easily applicable to images.
I've written a short script to outline how to adapt my above mentioned article for caching of thumbnails. see:
http://tzu.nme.at/php/cache.phps


george_a

For the best image quality...
How to get new proportional size of the image if the desible size of source image is approximatly equal to needed size. If needed size differs from source size on less than the user factor then transformation isn`t apply.
/**********************************************/
function imageCopyResize($image, $xSize, $ySize, $needed_user_factor, $new_image_path = "")
{
//example: neded_user_factor = 0.2
if($xSize == 0 || $ySize == 0)
   return array("At the leat one pair of size is 0",0,0);
$size = getImageSize($image);
$width = $size[0];
$height = $size[1];
$x_ratio = $xSize / $size[0];
$y_ratio = $ySize / $size[1];
if($x_ratio > $y_ratio)    $res_ratio = $y_ratio;
else $res_ratio = $x_ratio;
if(abs($res_ratio - 1) > $needed_user_factor)
   {
    $width = ceil($width * $res_ratio);
    $height = ceil($height * $res_ratio);
   }
$fileinfo = pathinfo($image);
$file_type = strtolower($fileinfo["extension"]);
if($file_type == "jpg" || $file_type == "jpeg")
   $src = ImageCreateFromJpeg($image);
else if($file_type == "gif")
   $src = ImageCreateFromGif($image);
else if($file_type == "png")
   $src = ImageCreateFromPNG($image);
else if($file_type == "bmp")    
   $src = ImageCreateFromBmp($image);    //Thanks Previous Coder
else
  return array("Unknown image format: ".$file_type, 0, 0);  
$output_path = ($new_image_path == "")?$image:$new_image_path;
$dst = ImageCreateTrueColor($width, $height);
ImageCopyResized($dst, $src, 0,0,0,0,$width, $height, $size[0], $size[1]);
if($file_type == "jpg" || $file_type == "jpeg")
   ImageJpeg($dst, $output_path, 100);
else if($file_type == "gif" || $file_type == "bmp")
    ImageGif($dst, $output_path);
else if($file_type == "png")
   ImagePNG($dst, $output_path);
ImageDestroy($src);
ImageDestroy($dst);
return array("", $width, $height);
}
/**********************************************/


spencejames2000

For anyone suffering from the srcX and srcY bug (some versions of gd ignore them completely - see http://bugs.php.net/bug.php?id=12780 for details), a quick solution is to use this code snippet:
<?php
function imgcopyresampled(&$dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
$tmp_img = imagecreatetruecolor($src_w, $src_h);
$rv2 = imagecopy($tmp_img, $src_img, 0,0, $src_x, $src_y, $src_w, $src_h);
$rv1 = imagecopyresampled($dst_img, $tmp_img, $dst_x,$dst_y, 0,0, $dst_w, $dst_h, $src_w, $src_h);
imagedestroy($tmp_img);
return($rv1 and $rv2);
}
?>
By using imagecopy to extract the relevant portion of the source image, it works a lot more quickly than pike's solution below, and also without the extra blur.
It may be useful to use override_function in existing projects, although I have not tested this myself.


info

For an internet photoalbum I was looking for a script which I could simply drop in a directory with images and which would do the rest.
Therefor I am using the following resize script now. I have made the little thumb-part because I want to have all the same size thumbnails, but with as less as possible distortion. Therefor, images with other dimensions are resized, but also cut off a little.
Als $pictype = thumb, the extra dimension calculations are used
$width and $height are the new dimensions of $filename, the image
$dest is the directory where the new image must be copied in.
The script:
// Resize function
function resize($filename, $dest, $width, $height, $pictype)
{
$format = strtolower(substr(strrchr($filename,"."),1));
switch($format)
{
case 'gif' :
$type ="gif";
$img = imagecreatefromgif($filename);
break;
case 'png' :
$type ="png";
$img = imagecreatefrompng($filename);
break;
case 'jpg' :
$type ="jpg";
$img = imagecreatefromjpeg($filename);
break;
case 'jpeg' :
$type ="jpg";
$img = imagecreatefromjpeg($filename);
break;
default :
die ("ERROR; UNSUPPORTED IMAGE TYPE");
break;
}

list($org_width, $org_height) = getimagesize($filename);
$xoffset = 0;
$yoffset = 0;
if ($pictype == "thumb") // To minimize destortion
{
if ($org_width / $width > $org_height/ $height)
{
$xtmp = $org_width;
$xratio = 1-((($org_width/$org_height)-($width/$height))/2);
$org_width = $org_width * $xratio;
$xoffset = ($xtmp - $org_width)/2;
}
elseif ($org_height/ $height > $org_width / $width)
{
$ytmp = $org_height;
$yratio = 1-((($width/$height)-($org_width/$org_height))/2);
$org_height = $org_height * $yratio;
$yoffset = ($ytmp - $org_height)/2;
}
}
$img_n=imagecreatetruecolor ($width, $height);
imagecopyresampled($img_n, $img, 0, 0, $xoffset, $yoffset, $width, $height, $org_width, $org_height);
if($type=="gif")
{
imagegif($img_n, $dest);
}
elseif($type=="jpg")
{
imagejpeg($img_n, $dest);
}
elseif($type=="png")
{
imagepng($img_n, $dest);
}
elseif($type=="bmp")
{
imagewbmp($img_n, $dest);
}
Return true;
}


mr bitmap

For all those that are using imagecreatefromwbmp() for.BMP files, I believe you are wrong.
imagecreatefromwbmp() is for WBMP image files used for WAP devices not windows BMP images.
I don't think PHP has any built in Windows BMP functions.
There are many examples here that make this mistake.
See the documentation for imagecreatefromwbmp()


tyron madlener tyron.at

Creating a thumbnail (120x90 pixel) of a big image (3000x2000 pixel) took me about 5 seconds with imagecopyresampled()
Thats pretty much, so I tested a little how I could improve the speed. I found that imagecopyresized is way faster but results in poor quality.
So I combined both - I first reduce the big image via imagecopyresized to 1024x768 pixel and then create the small thumbnail via imagecopyresampled. The resulting quality is almost the same. In my tests, resizing took only about 2.2 seconds now - twice as fast :)
I also tried using that bicubic image resizing function in some earlier post here, but it was only faster when the thumbnails were smaller than 120x90 and the quality was not very good.
Here's the code if you wanna (I guess there are still a few possibilites to do some more optimiztions tough):
<?php
function CreateThumb($file,$maxwdt,$maxhgt, $dest) {
list($owdt,$ohgt,$otype)=@getimagesize($file);
 switch($otype) {
   case 1:  $newimg=imagecreatefromgif($file); break;
   case 2:  $newimg=imagecreatefromjpeg($file); break;
   case 3:  $newimg=imagecreatefrompng($file); break;
   default: echo "Unkown filetype (file $file, typ $otype)"; return;
 }
   
 if($newimg) {
   if($owdt>1500 || $ohgt>1200)
list($owdt, $ohgt) = Resample($newimg, $owdt, $ohgt, 1024,768,0);

   Resample($newimg, $owdt, $ohgt, $maxwdt, $maxhgt);

if(!$dest) return $newimg;

if(!is_dir(dirname($dest)))
mkdir(dirname($dest));
   
   switch($otype) {
     case 1: imagegif($newimg,dest); break;    
     case 2: imagejpeg($newimg,$dest,90); break;
     case 3: imagepng($newimg,$dest);  break;
   }

imagedestroy($newimg);
   
   chmod($dest,0644);
 }
}
function Resample(&$img, $owdt, $ohgt, $maxwdt, $maxhgt, $quality=1) {
 if(!$maxwdt) $divwdt=0;
  else $divwdt=Max(1,$owdt/$maxwdt);
 
 if(!$maxhgt) $divhgt=0;
  else $divhgt=Max(1,$ohgt/$maxhgt);

 if($divwdt>=$divhgt) {
   $newwdt=$maxwdt;
   $newhgt=round($ohgt/$divwdt);
 } else {
   $newhgt=$maxhgt;
   $newwdt=round($owdt/$divhgt);
 }

$tn=imagecreatetruecolor($newwdt,$newhgt);
if($quality)
imagecopyresampled($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);
else
imagecopyresized($tn,$img,0,0,0,0,$newwdt,$newhgt,$owdt,$ohgt);
imagedestroy($img);

$img = $tn;

return array($newwdt, $newhgt);
}
?>


pie pie

Confirming on what fluffle said, and to say his code will also crop and resize an image what is smaller than 100x100 pixels if you want. This is important because it means your images no matter how you decide to rezise them, will maintain their aspect ratios and with a minimum amount of image loss.
//Get file type
$mime = $orig_image_mimetype;
$type = substr($mime, strpos($mime,'/')+1);
switch($type) {
case 'jpeg':
case 'pjpeg':
$big = imagecreatefromjpeg($file);
break;
case 'png':
case 'x-png':
$big = imagecreatefrompng($file);
break;
case 'gif':
$big = imagecreatefromgif($file);
break;
default:
return FALSE;
break;
}
The above code is what I use to support multiple file type resizing. I then use the same thing again when it's time to output the image using $result = imagejpeg($thumb,'',80), imagepng($thumb), and imagegif($thumb).


smrtak

class cobrazek
   {
       function resizeMaxJpeg($file,$mx,$my,$q=85)
       {
           $dst = cobrazek::resizeMax(imagecreatefromjpeg($file),$mx,$my);
           if(!$dst)
               return false;
           if(!imagejpeg($dst,$file,$q))
               return false;
           return true;
       }
       function resizeMax($src,$mx,$my)
       {
           //zjisti velikost
           $sx = imagesx($src);
           $sy = imagesy($src);
           //spocitej cilovou velikost
           $v = min(min($mx,$sx)/$sx,min($my,$sy)/$sy);
           $dx = $v*$sx;
           $dy = $v*$sy;
           $dst = imagecreatetruecolor($dx,$dy);
           //resample
           imagecopyresampled ($dst,$src,0,0,0,0,$dx,$dy,$sx,$sy);
           //vystup
           return $dst;
       }
   }


rich

Be wary of this function when resizing images to make them *larger* than the original due to the memory consumption rate. For example a 200KB JPEG file (1024x768) will take up 4MB of memory when loaded, but when resampled to twice the the size the memory use jumps to 20.1MB. imagecopyresized does the same. Allow approx. 5 bytes per *pixel* for memory allowance when dealing with true colour images.

liviu dot malaescu

3800x2500px - 2s
3807x6768 - 4.7s
Tested on a core2duo e4300/1gb ram - only one core used.
It reduces first with nearest-neighbour and then with bicubic on the smaller image.
Thumb quality is fine :)
<?php
$cale_in = "test.jpg"; //input-file
$cale_out = "test_thumb.jpg"; //output-file
$make_thumbs = "YES";
$thumbsize[0] = 100;
$thumbsize[1] = 75;
ini_set("memory_limit", "134217728"); // needed for huge pictures
// Bicubic resampling, not written by me
function ImageCopyResampleBicubic
(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)  {
ImagePaletteCopy ($dst_img, $src_img);
$rX = $src_w / $dst_w;
$rY = $src_h / $dst_h;
$w = 0;
for ($y = $dst_y; $y < $dst_h; $y++)  {
$ow = $w; $w = round(($y + 1) * $rY);
$t = 0;
for ($x = $dst_x; $x < $dst_w; $x++)  {
$r = $g = $b = 0; $a = 0;
$ot = $t; $t = round(($x + 1) * $rX);
for ($u = 0; $u < ($w - $ow); $u++)  {
for ($p = 0; $p < ($t - $ot); $p++)  {
$c = ImageColorsForIndex ($src_img,
ImageColorAt ($src_img, $ot + $p, $ow + $u));
$r += $c['red'];
$g += $c['green'];
$b += $c['blue'];
$a++;
}
}
ImageSetPixel ($dst_img, $x, $y,
ImageColorClosest ($dst_img, $r / $a, $g / $a, $b / $a));
}
}
}
function makeThumb($cale_in)  {
global $thumbsize;
$sursa = imagecreatefromjpeg($cale_in);
$is_jpeg = getimagesize($cale_in);
$ws = $is_jpeg[0];
$hs = $is_jpeg[1];
if($ws > $thumbsize[0] && $hs > $thumbsize[1])
{
$aspect = $ws/$hs;
if($aspect <= 1.333333)  {
$hd = $thumbsize[1];
$wd = floor($hd*$aspect);
}
else  {
$wd = $thumbsize[0];
$hd = floor($wd/$aspect);
}
$Z = ceil(log(($ws*$hs)/(4*$thumbsize[0]*$thumbsize[1])))+1;
if(log(($ws*$hs)/(4*$thumbsize[0]*$thumbsize[1])) < 0) $Z=1;
$dx = $dy = 0;
if($Z > 1) {
$dest = imagecreatetruecolor(round($ws/$Z), round($hs/$Z));
for($i=0; $i < $hs; $i+=$Z) {
for($j=0; $j < $ws; $j+=$Z) {
$rgb = imagecolorat($sursa, $j, $i);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$pcol = imagecolorallocate($dest, $r, $g, $b);
imagesetpixel($dest, $dx, $dy, $pcol);
$dx++;
}
$dx=0;
$dy++;
}
}
else
{
$dest = imagecreatetruecolor($ws, $hs);
imagecopy($dest, $sursa, 0, 0, 0, 0, $ws, $hs );
}
imagedestroy($sursa);
$destrs = imagecreatetruecolor($wd, $hd);
ImageCopyResampleBicubic($destrs,$dest,0,0,0,0,
$wd,$hd,round($ws/$Z),round($hs/$Z));
ImageJpeg($destrs, $cale_out, 100);
echo "Z:$Z <b>|</b> ($ws x $hs) -> ($wd x $hd) @ ".$ws/$hs;
}
}
function mf() {
list($usec, $sec) = explode(" ", microtime());
$x[0] = $sec;  $x[1] = $usec;
return $x;
}
$timp1 = mf(); //starting to count
makeThumb($cale_in); //makes the actual thumb
$timp2 = mf(); //timer ends
$dsec = $timp2[0] - $timp1[0];
$dusec = $timp2[1] - $timp1[1];
echo "<b>|</b> Time : <b>".round($dusec+$dsec,6)."s</b> <b>|</b><br />";
?>


phpman

<?php
function img_resize($path,$w=0,$h=0,$quality=100,$save=''){
 $image_data=@getimagesize($path);
 $image_type=$image_data[2];
 $gd_ext=array('','jpg','gif');
 if($image_type!=1&&$image_type!=2) return false;
 if($save=='') header('Content-type: '.$image_data['mime']); else $save=eregi_replace('%ext',$gd_ext[$image_type],$save);
 if($w!=0){
   $rapporto=$image_data[0]/$w;
   if($h!=0){
     if($image_data[1]/$rapporto>$h) $rapporto=$image_data[1]/$h;
   }
 }elseif($h!=0){
   $tmp_h=$image_data[1]/$h;
 }else{
   return false;
 }
 $thumb_w=$image_data[0]/$rapporto;
 $thumb_h=$image_data[1]/$rapporto;
 if($image_type==1) $img_src=@imagecreatefromgif($path);
 elseif($image_type==2) $img_src=@imagecreatefromjpeg($path);
 $img_thumb=@imagecreatetruecolor($thumb_w,$thumb_h);
 $result=@imagecopyresampled($img_thumb,$img_src,
0,0,0,0,$thumb_w,$thumb_h,$image_data[0],$image_data[1]);
 if(!$img_src||!$img_thumb||!$result) return false;
 if($image_type==1) $result=@imagegif($img_thumb,$save);
 elseif($image_type==2) $result=@imagejpeg($img_thumb,$save,$quality);
 return $result;
}
?>
This script resize images. It can also make thumbs. It use the resample of images for hight quality result.
It can show the result or save it (if $save isn't null).
It respect the width and/or the height of image.
It can replace the destination file extestion dinamically (filename.%ext)
Support gif & jpg.
Return false if something goes wrong.


areddan

<?php
// The file
$filein = ''; // File in
$fileout = 'ttt.gif'; // Fileout - optional
$imagethumbsize_w = 100; // thumbnail size (area cropped in middle of image)
$imagethumbsize_h = 75; // thumbnail size (area cropped in middle of image)
resize_then_crop( $filein,$fileout,$imagethumbsize_w,
$imagethumbsize_h,/*rgb*/"255","255","255");
//Author Alan Reddan Silverarm Solutions
//Date 27/01/2005
//Function that works well with images.
//It takes the image and reduces its size to best fit. i.e If you have an image
//that is 200 X 100 and you want a thumbnail of 75 X 50,
//it first resizes the image to 100 X 50
//and then takes out a portion 75 X 50 from then center of the input image.
//So loads of image information is retained.
//The corollary also holds if your input image is 100 X 200
//it first resizes image to 75 X 150 and then takes out a
//portion 75 X 75 from the centre
// The advantage here is that function decides on whether
//resize is by width or height itself.
//it also decides whether to use the height or the width as the base start point
//in the case that athumbnail is rectangular
function resize_then_crop( $filein,$fileout,
$imagethumbsize_w,$imagethumbsize_h,$red,$green,$blue)
{
// Get new dimensions
list($width, $height) = getimagesize($filein);
$new_width = $width * $percent;
$new_height = $height * $percent;
  if(preg_match("/.jpg/i", "$filein"))
  {
      $format = 'image/jpeg';
  }
  if (preg_match("/.gif/i", "$filein"))
  {
      $format = 'image/gif';
  }
  if(preg_match("/.png/i", "$filein"))
  {
      $format = 'image/png';
  }
 
      switch($format)
      {
          case 'image/jpeg':
          $image = imagecreatefromjpeg($filein);
          break;
          case 'image/gif';
          $image = imagecreatefromgif($filein);
          break;
          case 'image/png':
          $image = imagecreatefrompng($filein);
          break;
      }
$width = $imagethumbsize_w ;
$height = $imagethumbsize_h ;
list($width_orig, $height_orig) = getimagesize($filein);
if ($width_orig < $height_orig) {
 $height = ($imagethumbsize_w / $width_orig) * $height_orig;
} else {
   $width = ($imagethumbsize_h / $height_orig) * $width_orig;
}
if ($width < $imagethumbsize_w)
//if the width is smaller than supplied thumbnail size
{
$width = $imagethumbsize_w;
$height = ($imagethumbsize_w/ $width_orig) * $height_orig;;
}
if ($height < $imagethumbsize_h)
//if the height is smaller than supplied thumbnail size
{
$height = $imagethumbsize_h;
$width = ($imagethumbsize_h / $height_orig) * $width_orig;
}
$thumb = imagecreatetruecolor($width , $height);  
$bgcolor = imagecolorallocate($thumb, $red, $green, $blue);  
ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
imagealphablending($thumb, true);
imagecopyresampled($thumb, $image, 0, 0, 0, 0,
$width, $height, $width_orig, $height_orig);
$thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
// true color for best quality
$bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);  
ImageFilledRectangle($thumb2, 0, 0,
$imagethumbsize_w , $imagethumbsize_h , $white);
imagealphablending($thumb2, true);
$w1 =($width/2) - ($imagethumbsize_w/2);
$h1 = ($height/2) - ($imagethumbsize_h/2);
imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1,
$imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);
// Output
//header('Content-type: image/gif');
//imagegif($thumb); //output to browser first image when testing
if ($fileout !="")imagegif($thumb2, $fileout); //write to file
header('Content-type: image/gif');
imagegif($thumb2); //output to browser
}
?>


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