One more version of setMemoryForImage (see below)
function setMemoryForImage($filename)
{
$imageInfo = getimagesize($filename);
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);
$memoryLimit = (int) ini_get('memory_limit')*1048576;
if ((memory_get_usage() + $memoryNeeded) > $memoryLimit)
{
ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
return (true);
}
else return(false);
}
//work's it. no problem!
imagecopyresized
(PHP 4, PHP 5)
imagecopyresized — Copy and resize part of an image
Description
imagecopyresized() copies a rectangular portion of one image to another image. dst_image is the destination image, src_image is the source image identifier.
In other words, imagecopyresized() will take an rectangular area from src_image of width src_w and height src_h at position (src_x ,src_y ) and place it in a rectangular area of dst_image of width dst_w and height dst_h at position (dst_x ,dst_y ).
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
Example #1 Resizing an image
This example will display the image at half size.
<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-type: image/jpeg');
// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
// Output
imagejpeg($thumb);
?>
The above example will output something similar to:
The image will be output at half size, though better quality could be obtained using imagecopyresampled().
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().
See Also
imagecopyresized
14-Oct-2007 08:09
24-Jul-2007 01:11
Create thumbnail in GIF format for JPEG and GIF ( with or without transparency, for animated GIF, only the first frame is retained ) originals, thumbnails for PNG images should save in PNG format to support alpha transparency.
For JPEG image and GIF without transparency, simply use imagecopyresized will be OK. For GIF with transparency, we should first understand the behavior of imagecopyresized: it extracts pixels that are not transparent from the specified rectangle area of the source image, resizs the rectangle, probably does some color approximation, then copys to the target image. Suppose that you want to put a picture frame image( only the border is non-transparent ) over a photo( opaque ) to compose a final image, just imagecopyresize the picture frame image to the photo will be OK. To better understand the behavior, consider the case you want to copy several GIF images with transparency together to form a new one, note that the GIF image can only have one transparent color, if the old transparent colors are not dropped by imagecopyresize, it will be confused which color from the originals will be the transparent color in the final image. So imagecopyresize does the right thing. To this point, it is not hard to understand why some people get a black background when they want to create thumbnails for transparent GIF: the original transparent pixels are gone, and the non-transparent pixels are put onto an empty canvas( no color allocated ). Then we arrive
<?php
$im = imagecreatefromgif( 'test.gif' );
// or $im = imagecreatefromjpeg( 'test.jpg' );
$mw = 360; // max width
$mh = 360; // max height
$ow = imagesx( $im );
$oh = imagesy( $im );
if( $ow > $mw || $oh > $mh ) {
if( $ow > $oh ) {
$tnw = $mw;
$tnh = $tnw * $oh / $ow;
} else {
$tnh = $mh;
$tnw = $tnh * $ow / $oh;
}
} else {
// although within size restriction, we still do the copy/resize process
// which can make an animated GIF still
$tnw = $ow;
$tnh = $oh;
}
// the document recommends you to use truecolor to get better result
$imtn = imagecreatetruecolor( $tnw, $tnh );
// if the image has transparent color, we first extract the RGB value of it,
// then use this color to fill the thumbnail image as the background. This color
// is safe to be assigned as the new transparent color later on because it will
// be filtered by imagecopyresize.
$originaltransparentcolor = imagecolortransparent( $im );
if(
$originaltransparentcolor >= 0 // -1 for opaque image
&& $originaltransparentcolor < imagecolorstotal( $im )
// for animated GIF, imagecolortransparent will return a color index larger
// than total colors, in this case the image is treated as opaque ( actually
// it is opaque )
) {
$transparentcolor = imagecolorsforindex( $im, $originaltransparentcolor );
$newtransparentcolor = imagecolorallocate(
$imtn,
$transparentcolor['red'],
$transparentcolor['green'],
$transparentcolor['blue']
);
// for true color image, we must fill the background manually
imagefill( $imtn, 0, 0, $newtransparentcolor );
// assign the transparent color in the thumbnail image
imagecolortransparent( $imtn, $newtransparentcolor );
}
// copy/resize as usual
imagecopyresized( $imtn, $im, 0, 0, 0, 0, $tnw, $tnh, $ow, $oh );
imagegif( $imtn, 'test.thumbnail.gif' );
imagedestroy( $im );
imagedestroy( $imtn );
?>
Only do imagecolortransparent( $thumbnail, imagecolortransparent( $source ) ); some times works, just because the color indexes for background transparent pixels in the two images happens to be the same.
PHP5.2.0 with GD bundled (2.0.28 compatible)
08-Jun-2007 08:52
Regarding ob at babcom dot biz's function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)
Make sure to not use a quality of 9 or higher for png resizing.
PHP will output an error like:
fatal libpng error: zlib failed to initialize compressor
or
gd-png error: setjmp returns error condition
23-Mar-2007 01:34
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.
Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
* Author : Halit YESIL
* www : www.halityesil.com, www.prografik.net, www.trteknik.net
* email : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
* GSM : +90.535 648 3504
* Create Date : 21 / 03 / 2007
*
*
* Script : Image resize and croping class.
* You can Write copyright text and attach your logo write on image with this class
*
*
* $obj = new pg_image($arg);
*
*
* Varibles Information
* [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
* [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
* [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
* [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
* [4] width => (integer) => Target File Width
* [5] height => (integer) => Target File Height
* [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
* [7] action => (crop | resize) => Target Action "resize" OR "crop"
* [8] bordersize => (integer 0-5) => Target Border Size
* [9] bordercolor => (color hex) => Target Border Color
* [10] bgcolor => (color hex) => Target Background Color
* [11] copytext => (String) => Copyright Content Text
* [12] copycolor => (color hex) => Copyright Text Color
* [13] copyshadow => (color hex) => Copyright Text Shadow color
* [14] copybgcolor => (color hex) => Copyright Background Color
* [15] copybgshadow => (color hex) => Copyright Background Shadow Color
* [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
* [17] copybordercolor => (color hex) => Copyright Border Color
* [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
* [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
* [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
*
*
*
*
*/
<?php
$source = ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
$arg =array( type =>'FILE',
file =>false,
path =>$source,
target =>'',
width =>150,
height =>50,
quality =>80,
action =>'resize',
bordersize =>1,
bordercolor =>'#00CCFF',
bgcolor =>'#000000',
copytext =>'Bodrum 1998',
copycolor =>'#FFFFFF',
//copyshadow =>'#000000',
//copybgcolor =>'#D0FFCC',
//copybgshadow =>'#656565',
copybordersize =>0,
copybordercolor =>'#FFFFFF',
copyposition =>'bottom',
logoposition =>'topleft',
logoimage =>'logo.png');
//$arg = "$source,,400,300,80,resize";
new pg_image($arg);
?>
15-Nov-2006 09:23
This code convert images to thumbs.
How he work -
Check source image - Width and Height,
crop a maximum from original image,
resize croped to user defined size
// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);
<?php
function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){
//$src = original image location
//$dst = destination image location
//$dstx = user defined width of image
//$dsty = user defined height of image
$allowedExtensions = 'jpg jpeg gif png';
$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);
for($i=0; count($extensions)>$i; $i=$i+1){
if($extensions[$i]==$currentExtensions)
{ $extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}
if($extensionOK){
$size = getImageSize($src);
$width = $size[0];
$height = $size[1];
if($width >= $dstx AND $height >= $dsty){
$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;
if($proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;
$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
($target['height']*$target['height']))/2);
$crop = round($original['diagonal_center'] - $target['diagonal_center']);
if($proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] = round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}
if($fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif ($fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif ($fileExtension == 'png'){
$from = imageCreateFromPNG($src);
}
$new = ImageCreateTrueColor ($dstx,$dsty);
imagecopyresampled ($new, $from, 0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);
if($fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif ($fileExtension == "gif"){
imagegif($new, $dst);
}elseif ($fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}
?>
15-Sep-2006 10:38
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified. This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.
For example, if you have an image that is 800x600 and you specify your new image to be 400x200, it will resize based on the smallest number (in this case 200) and maintain the images 1:1 ratio. So your final image would end up at something like 262x200.
UPDATE: I have updated this function, I added the 'newdir' option in case you want the images saved in a different directory than the script. I also fixed the thumbnail slice so it is perfectly in the center now and fixed the bug that 'ob at babcom dot biz' mentioned so you can safely resize based on width or height now.
<?
/**********************************************************
* function resizejpeg:
*
* = creates a resized image based on the max width
* specified as well as generates a thumbnail from
* a rectangle cut from the middle of the image.
*
* @dir = directory image is stored in
* @newdir = directory new image will be stored in
* @img = the image name
* @max_w = the max width of the resized image
* @max_h = the max height of the resized image
* @th_w = the width of the thumbnail
* @th_h = the height of the thumbnail
*
**********************************************************/
function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
// set destination directory
if (!$newdir) $newdir = $dir;
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image?
if ($or_w > $max_w || $or_h > $max_h) {
// resize by height, then width (height dominant)
if ($max_h < $max_w) {
$rs_h = $max_h;
$rs_w = $rs_h / $ratio;
}
// resize by width, then height (width dominant)
else {
$rs_w = $max_w;
$rs_h = $ratio * $rs_w;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
}
// image requires no resizing
else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $newdir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 2) - ($th_w / 2));
$new_h = (($rs_h / 2) - ($th_h / 2));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $newdir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
?>
Example:
<?php
$dir = './';
$img = 'test.jpg';
resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>
The example would resize the image 'test.jpg' into something 600x400 or less (retains the 1:1 ratio of the image) and creates the file 'thumb_test.jpg' at 300x150.
23-Aug-2006 09:06
Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image. The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.
The code has been commented to help you read through it. The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.
<?php
/**
* Compose a PNG file over a src file.
* If new width/ height are defined, then resize the PNG (and keep all the transparency info)
* Author: Alex Le - http://www.alexle.net
*/
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
if( $ovr_w && $ovr_h )
$ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );
/* Noew compose the 2 images */
imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}
/**
* Resize a PNG file with transparency to given dimensions
* and still retain the alpha channel information
* Author: Alex Le - http://www.alexle.net
*/
function imageResizeAlpha(&$src, $w, $h)
{
/* create a new image with the new width and height */
$temp = imagecreatetruecolor($w, $h);
/* making the new image transparent */
$background = imagecolorallocate($temp, 0, 0, 0);
ImageColorTransparent($temp, $background); // make the new temp image all transparent
imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel
/* Resize the PNG file */
/* use imagecopyresized to gain some performance but loose some quality */
imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
/* use imagecopyresampled if you concern more about the quality */
//imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
return $temp;
}
?>
Example usage:
<?php
header('Content-type: image/png');
/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');
$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);
/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );
/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );
/**
* Open the same PNG file then compose without resizing
* As the original $watermark is passed by reference, it was resized already.
* So we have to reopen it.
*/
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser
ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
21-Aug-2006 08:32
Regarding the note and function of kyle.florence on August 3rd 2006:
I tried to use his function resizejpeg() for resizing images in my gallery. As far as I can tell it contains a small bug.
Resizing worked fine as long as I had the same maximum width and maximum height specified. Wanting all thumbnails to have the same height - so my images would appear in a straight line on my website both in portrait format and in landscape format - I soon encountered the problem that resizing with different values of maximum width and maximum height would not work proberly.
If you are using the script change the following 2 lines where the resized width and the resized height are calculated:
<?php
$rs_h = $ratio * $max_h;
?>
should be:
<?php
$rs_h = $ratio * $rs_w;
?>
and:
<?php
$rs_w = $max_w / $ratio;
?>
should be:
<?php
$rs_w = $rs_h / $ratio;
?>
The following function is based on Kyle Florence's function. I left out the thumbnail-part and rather added the possibiliy of defining a new dir and new filename for the image. If you need to resize and then create a thumbnail just run the function twice. Here, the thumbnail will contain the full picture and not a cutout of the original image.
The function supports JPG, GIF and PNG resizing. The quality in case of JPG is given to the function as the last parameter $Quality.
The variable names should speak for their usage.
<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
$ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
($TypeCode==3?"png":FALSE)));
$CreateFunction="imagecreatefrom".$ImageType;
$OutputFunction="image".$ImageType;
if ($ImageType) {
$Ratio=($ImageHeight/$ImageWidth);
$ImageSource=$CreateFunction($Dir.$Image);
if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
if ($ImageWidth > $MaxWidth) {
$ResizedWidth=$MaxWidth;
$ResizedHeight=$ResizedWidth*$Ratio;
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
}
if ($ResizedHeight > $MaxHeight) {
$ResizedHeight=$MaxHeight;
$ResizedWidth=$ResizedHeight/$Ratio;
}
$ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
$ResizedHeight,$ImageWidth,$ImageHeight);
}
else {
$ResizedWidth=$ImageWidth;
$ResizedHeight=$ImageHeight;
$ResizedImage=$ImageSource;
}
$OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
return true;
}
else
return false;
}
?>
Before calling the function support for JPG, PNG or GIF should be checked.
08-Aug-2006 08:37
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.
None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.
However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.
[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
03-Aug-2006 10:43
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.
<?php
/**********************************************************
* function resizejpeg:
*
* = creates a resized image based on the max width
* specified as well as generates a thumbnail from
* a rectangle cut from the middle of the image.
*
* @dir = directory image is stored in
* @img = the image name
* @max_w = the max width of the resized image
* @max_h = the max height of the resized image
* @th_w = the width of the thumbnail
* @th_h = the height of the thumbnail
*
**********************************************************/
function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
// get original images width and height
list($or_w, $or_h, $or_t) = getimagesize($dir.$img);
// make sure image is a jpeg
if ($or_t == 2) {
// obtain the image's ratio
$ratio = ($or_h / $or_w);
// original image
$or_image = imagecreatefromjpeg($dir.$img);
// resize image
if ($or_w > $max_w || $or_h > $max_h) {
// first resize by width (less than $max_w)
if ($or_w > $max_w) {
$rs_w = $max_w;
$rs_h = $ratio * $max_h;
} else {
$rs_w = $or_w;
$rs_h = $or_h;
}
// then resize by height (less than $max_h)
if ($rs_h > $max_h) {
$rs_w = $max_w / $ratio;
$rs_h = $max_h;
}
// copy old image to new image
$rs_image = imagecreatetruecolor($rs_w, $rs_h);
imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
} else {
$rs_w = $or_w;
$rs_h = $or_h;
$rs_image = $or_image;
}
// generate resized image
imagejpeg($rs_image, $dir.$img, 100);
$th_image = imagecreatetruecolor($th_w, $th_h);
// cut out a rectangle from the resized image and store in thumbnail
$new_w = (($rs_w / 4));
$new_h = (($rs_h / 4));
imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);
// generate thumbnail
imagejpeg($th_image, $dir.'thumb_'.$img, 100);
return true;
}
// Image type was not jpeg!
else {
return false;
}
}
?>
Example:
<?php
$dir = './';
$img = 'test.jpg';
resizejpeg($dir, $img, 600, 600, 300, 150);
?>
The example would resize the image 'test.jpg' into something 600x600 or less (1:1 ratio) and create the file 'thumb_test.jpg' at 300x150.
21-Apr-2006 10:05
I was fiddling with this a few days trying to figure out how to resize the original images on my website, but this site:
http://www.sitepoint.com/article/image-resizing-php
Has a great tutorial on using PHP to resize images without creating thumbnails. It was exactly what I was looking to do.
15-Feb-2006 11:42
Function creates a thumbnail from the source image, resizes it so that it fits the desired thumb width and height or fills it grabbing maximum image part and resizing it, and lastly writes it to destination
<?
function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
list($width, $height) = getimagesize($filename);
$source = imagecreatefromjpeg($filename);
if($width > $th_width || $height > $th_height){
$a = $th_width/$th_height;
$b = $width/$height;
if(($a > $b)^$forcefill)
{
$src_rect_width = $a * $height;
$src_rect_height = $height;
if(!$forcefill)
{
$src_rect_width = $width;
$th_width = $th_height/$height*$width;
}
}
else
{
$src_rect_height = $width/$a;
$src_rect_width = $width;
if(!$forcefill)
{
$src_rect_height = $height;
$th_height = $th_width/$width*$height;
}
}
$src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
$src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);
$thumb = imagecreatetruecolor($th_width, $th_height);
imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);
imagejpeg($thumb,$destination);
}
}
?>
04-Oct-2005 04:07
imagecopyresized() does not do any resampling. This makes it extremely quick. If quality is an issue, use imagecopyresampled().
11-Aug-2005 11:24
simple script for creating thumbnails with process information and saving original ratio thumbnail to new destination...good then useing with upload or uploaded images:
<?php
//Upload------------------------------------
if(isset( $submit ))
{
if ($_FILES['imagefile']['type'] == "image/jpeg"){
copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
or die ("Could not copy");
echo "";
echo "Image Name: ".$_FILES['imagefile']['name']."";
echo "<br>Image Size: ".$_FILES['imagefile']['size']."";
echo "<br>Image Type: ".$_FILES['imagefile']['type']."";
echo "<br>Image Copy Done....<br>";
}
else {
echo "<br><br>";
echo "bad file type (".$_FILES['imagefile']['name'].")<br>";exit;
}
//-----upload end
//------start thumbnailer
$thumbsize=120;
echo "Thumbnail Info: <br>
1.Thumb defined size: - OK: $thumbsize<br>";
$imgfile = "../images/$imagefile_name";//processed image
echo "
2.Image destination: - OK: $imgfile<br>";
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
echo "3.Image size - OK: W=$width x H=$height<br>";
$imgratio=$width/$height;
echo "3.Image ratio - OK: $imgratio<br>";
if ($imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
echo "4.Thumb new size -OK: W=$newwidth x H=$newheight<br>";
$thumb = ImageCreateTrueColor($newwidth,$newheight);
echo "5.TrueColor - OK<br>";
$source = imagecreatefromjpeg($imgfile);
echo "6.From JPG - OK<br>";
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK<br>";
//-----------end--------------
?>
or without any info, just resizing:
<?php
//------start thumbnailer
$thumbsize=120;
$imgfile = "../images/$imagefile_name";
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($imgfile);
$imgratio=$width/$height;
if ($imgratio>1){
$newwidth = $thumbsize;
$newheight = $thumbsize/$imgratio;}
else{
$newheight = $thumbsize;
$newwidth = $thumbsize*$imgratio;}
$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = imagecreatefromjpeg($imgfile);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------end--------------
?>
i hope it helps.
10-Aug-2005 02:35
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
preg_match("'^(.