I've created a PHP5 image resize class, using ImageCopyResampled, that someone might find useful, with support for JPEG, PNG, and GIF formats. It retains the original image's aspect ratio when resizing, and doesn't resize or resample if the original width and height is smaller then the desired resize.

The ultimate smart image re-sizing routine. You provide the original image, and a desired width and/or height. The function will intelligently re-size the original image to fit, centered, within the specified dimensions. Either width or height can be omitted to have the re-size "lock" only on width or height. Fantastic for thumbnail generation. Designed to work with PNG's.

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.

Having updated GD-Library from 2.0.35-r1 to 2.0.35-r3 using negative numbers for $dstX or $dstY started to produce unpredictable results, such as inserting shrinked images and enlarging $dstH or $dstW all by itself. While it did work fine previously, one should avoid using or calculating negative numbers for imagecopyresampled from the beginning.

I hated that enlarging an image resulted in giant pixels rather than a smoother look, so I wrote this function. It takes longer, but gives a much nicer look.

<?php

function imagecopyresampledSMOOTH(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mult=1.25){// don't use a $mult that's too close to an int or this function won't make much of a difference

// if the current step w/h is larger than the final height, adjust it back to the final size // this check also makes it so that if we are doing a resize to smaller image, it happens in one step (since that's already smooth)if($tgt_w > $dst_w){ $tgt_w = $dst_w; } if($tgt_h > $dst_h){ $tgt_h = $dst_h; }

// as long as the final w/h has not been reached, reep on resizingif($tgt_w < $dst_w OR $tgt_h < $dst_h){imagecopyresampledSMOOTH($dst_img, $dst_img, $dst_x, $dst_y, $dst_x, $dst_y, $dst_w, $dst_h, $tgt_w, $tgt_h, $mult); }}

I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.

Another add-on to previous php5 class for thumbnail (with a merge of Matt and Zorro's proposals).
This is dedicated to generate thumbnail on the fly for a webpage using the subclass thumbnail.
It saves the generated thumb as myimage_tn, in the same directory.
I'm quite new with php5, so I think this could be optimized, but it seems to work fine.

Resampling GIFs and retain transparency dosen't work always, as dependent on the resample factor the resulting resampled image has some pattern-noise that prevents "imagegif" to find all the transparent-pixels.One way to fix this, is to reset all pixels with high alpha to full-transparent:<?php// load/create images$img_src=imagecreatefromgif($g_srcfile);$img_dst=imagecreatetruecolor($g_iw,$g_ih);imagealphablending($img_dst, false);

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.

Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.

Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.

<?php

// $image is $_FILES[ <image name> ]// $imageId is the id used in a database or wherever for this image// $thumbWidth and $thumbHeight are desired dimensions for the thumbnailfunction processImage( $image, $imageId, $thumbWidth, $thumbHeight ){$type = $image[ 'type' ];$galleryPath = 'images/collection/';

Here's a little function I wrote to resize images to a maximum dimension - based on what facebook does in the galleries. You put in a source, destination and a maximum dimension in pixels (eg 300), and for example if the image is long and thin, the longest edge will be 300px, yet the image retains proportions. A square image will become 300x300, a 6x4 (landscape) will become 300x200, a 4x6 (portrait) - 200x300 etc.It works on jpg images, but other formats can easily be added.<?phpfunction createThumb($spath, $dpath, $maxd) {$src=@imagecreatefromjpeg($spath); if (!$src) {return false;} else {$srcw=imagesx($src);$srch=imagesy($src); if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);} else {$width=$maxd;$height=floor($srch*$width/$srcw);} if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;} //if image is actually smaller than you want, leave small (remove this line to resize anyway)$thumb=imagecreatetruecolor($width, $height); if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));} else {imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}imagejpeg($thumb, $dpath); return true; }}?>

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.

Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.

R1 contains all of the original pixel data. If R2 goes outside of R1 in any direction, then R2 will contain stuff that doesn't help. A lot of the time R2 == R1 exactly.

R3 defines the area that holds the resampled image data. If R4 goes outside of R3 in any direction, then the resampled image data in R4 will be clipped by R3. In other words, R3 has the final say as to which of R4's pixels will be included in the final image. Most of the time, R4 == R3.

In the end, R2 (and the pixels in it) will be strecthed, squeezed, and placed exactly over R4.

There are plenty of good examples on this page to create thumbnails etc. But what if R3 was not destined to be a thumbnail? What if we wanted to take the entire R1 image and shrink it to fit inside R2 for example, leaving the original picture as a border? With the knowledge we have just gained it is a simple matter of creating the Source & Destination Images from the same .jpg file, then R2 should be equal to R1, and R4 should be smaller and completely inside R3.

When we think of these rectangles as tools and not images, it becomes easier to see what's going on.

This function is taken from lots of web sources so thanks to all for posting. It creates square or landscape thumbnails from .jpgs from either portait or landscape original images. I decide in advance which way I want the thumbs to display for consistency. I usually sharpen the images as well post-upload, to save on server resources. I can post this code if anyone wants it. I hope this helps someone...

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.

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.

Here's a simple plug-and-play replacement to imagecopyresampled that will deliver results that are almost identical except MUCH faster (very typically 30 times faster). I've been using this function for a few years but figured everyone could benefit from it.

For example, a 10 megapixel camera image (3872x2592 resolution) converted to thumbnail size using the default quality is 60 times faster than using imagecopyresampled (only 0.15 seconds from 8.9 seconds) and the image quality is almost identical. There's also an optional "quality" parameter that allows you to select the quality you want (1 is lowest quality but fastest, 5 is highest quality but slowest, 3 is default). All existing imagecopyresampled parameters fully work so it's truly plug-and-play. It also automatically decides if it would be better to just use imagecopyresampled depending on source and destination image sizes.

My image analysis shows imagecopyresized renders on average 2.4% of pixels significantly different than imagecopyresampled. These significantly different pixels give imagecopyresized the jagged, blocky, aliasing look. Using fastimagecopyresampled with a quality of 2, the significantly different pixel rate is reduced to 0.8%. With a quality of 3 (the default) it's reduced to 0.5% and at a quality of 4 it's reduced to only 0.03% but is still very typically 10-15 times faster for thumbnail creation.

Enjoy!

<?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: 12/17/04 - Project: FreeRingers.net - Freely distributable. // // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. // 1 = Up to 600 times faster. Poor results, just uses imagecopyresized but removes black edges. // 2 = Up to 95 times faster. Images may appear too sharp, some people may prefer it. // 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled. // 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images. // 5 = No speedup. Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled.

imagecopyresampled() works amazingly well, but here is something NOT to try with it:

The resize routine I wrote looks for pixel widths, and resizes images based on the notion that if their widths and heights are too big, so are their byte sizes. It worked out well at first.

But when I saw huge byte-size images slipping through beneath my 1000px-wide benchmark, I figured I'd subject the smaller-width images to resizing if their filesize() exceeded 100K.

The idea was that I'd "resize" them keeping their original widths and heights (i.e. in (1) below, $newW = $oldW, $newH = $oldH), and letting the "75" at (2) below reduce the byte size.

DON'T try that. imagecopyresampled() will lock up the server trying to resize an 800px-wide image to a "new" width of 800px. (I caught that on my Windows server before ever putting it on the destination Linux server, so take that with a grain of salt.)

I got around it by making $newW = ($picW * 0.99), etc. You get the byte-size reduction you want without locking up.

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

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

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

The suggestion of converting a gif to a png to retain transparency was useful. However the steps used to maintain the transparency work for a gif as well, so the conversion step is not necessary. Just do everything the same, and save as a gif anyway. i.e.

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.

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.

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), andformat 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 largerif ($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 elseimagepng($imgOut,"[out]");echo "Image created successfully: $outWidth x $outHeight, ".round(filesize("[source]")/1024)." KB<br>";imagedestroy($imgSrc);imagedestroy($imgOut);?>I just use this as a loop to create thumbnails for a series of ordered images.

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.

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

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.

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.

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

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.

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