PHP 8.3.22 Released!

Voting

: nine plus zero?
(Example: nine)

The Note You're Voting On

kyle(dot)florence(_[at]_)gmail(dot)com
18 years ago
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.

<< Back to user notes page

To Top