/    Sign up×
Community /Pin to ProfileBookmark

I need help cropping an image using GD

I want to crop a 80×80 thumbnail from the center of an image using GD. I am currently using the function below, which I copied from [URL=”http://911-need-code-help.blogspot.com/2008/10/resize-images-using-phpgd-library.html”]http://911-need-code-help.blogspot.com/2008/10/resize-images-using-phpgd-library.html[/URL]. However, if either the width or the height of the image is smaller than 80px, the thumbnail will be smaller than 80×80.
Is there a way to resize the image smaller than 80×80 to 80x(a number larger than 80) and then crop 80×80 from the center of the image?

For example, if the image is 80×40, then it gets resized to 160×80. Then, 80×80 is cropped from it.

Or, if there’s an easier way to get an 80×80 thumbnail, can someone provide an example? Thanks in advance.

The following the function I’m currently using:

[code=php] define( ‘THUMBNAIL_IMAGE_MAX_WIDTH’, 80 );
define( ‘THUMBNAIL_IMAGE_MAX_HEIGHT’, 80 );
function generate_image_thumbnail( $source_image_path, $thumbnail_image_path )
{
list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path );

switch ( $source_image_type )
{
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif( $source_image_path );
break;

case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg( $source_image_path );
break;

case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng( $source_image_path );
break;
}

if ( $source_gd_image === false )
{
return false;
}

$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;

$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height;

$thumbnail_small_width = $thumbnail_image_width / $source_image_width;
$thumbnail_small_height = $thumbnail_image_height / $source_image_height;

if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height )
{
$thumbnail_image_width = $source_image_width * $thumbnail_small_width;
$thumbnail_image_height = $source_image_height * $thumbnail_small_height;
}
if ( $thumbnail_aspect_ratio > $source_aspect_ratio )
{
//I think the math needs to be edited here
$thumbnail_image_width = ( int ) ( $thumbnail_image_height * $source_aspect_ratio );
}
else
{
//It needs to be edited here as well
$thumbnail_image_height = ( int ) ( $thumbnail_image_width / $source_aspect_ratio );
}

$thumbnail_gd_image = imagecreatetruecolor( $thumbnail_image_width, $thumbnail_image_height );

imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height );

imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 90 );

imagedestroy( $source_gd_image );

imagedestroy( $thumbnail_gd_image );

return true;
}[/code]

to post a comment
PHP

9 Comments(s)

Copy linkTweet thisAlerts:
@narutodude000authorJul 22.2010 — Help? Anyone?
Copy linkTweet thisAlerts:
@narutodude000authorJul 22.2010 — [code=php] if ( $source_image_width <= $thumbnail_image_width && $source_image_height <= $thumbnail_image_height )
{
if ( $source_image_height > $source_image_width )
{
$thumbnail_image_height = ( int ) ( $thumbnail_image_height / $source_aspect_ratio );
}
else
{
$thumbnail_image_width = ( int ) ( $thumbnail_image_width / $source_aspect_ratio );
}
}
if ( $thumbnail_aspect_ratio > $source_aspect_ratio )
{
$thumbnail_image_height = ( int ) ( $thumbnail_image_height / $source_aspect_ratio );
}
else
{
$thumbnail_image_width = ( int ) ( $thumbnail_image_width / $source_aspect_ratio );
}[/code]

I changed the above, which should create an image with one side being 80px, and another side being larger than 80px. Then, how do I crop it using imagecopyresampled?
Copy linkTweet thisAlerts:
@NogDogJul 22.2010 — I don't know if this will help, but it's the resizing function I use on this page:
[code=php]
/**
* Resize image
* @return mixed Image resource, or boolean false
* @param resource Image resource
* @param int width
* @param int height
*/
function resize($imgFile, $width, $height, &$error = null)
{
$attrs = @getimagesize($imgFile);
if($attrs == false or $attrs[2] != IMG_JPEG)
{
$error = "Uploaded image is not JPEG or is not readable by this page.";
return false;
}
if($attrs[0] * $attrs[1] > 3000000)
{
$error = "Max pixels allowed is 3,000,000. Your {$attrs[0]} x " .
"{$attrs[1]} image has " . $attrs[0] * $attrs[1] . " pixels.";
return false;
}
$ratio = (($attrs[0] / $attrs[1]) < ($width / $height)) ?
$width / $attrs[0] : $height / $attrs[1];
$x = max(0, round($attrs[0] / 2 - ($width / 2) / $ratio));
$y = max(0, round($attrs[1] / 2 - ($height / 2) / $ratio));
$src = imagecreatefromjpeg($imgFile);
if($src == false)
{
$error = "Unknown problem trying to open uploaded image.";
return false;
}
$resized = imagecreatetruecolor($width, $height);
$result = imagecopyresampled($resized, $src, 0, 0, $x, $y, $width, $height,
round($width / $ratio, 0), round($height / $ratio));
if($result == false)
{
$error = "Error trying to resize and crop image.";
return false;
}
else
{
return $resized;
}
}[/code]
Copy linkTweet thisAlerts:
@narutodude000authorJul 22.2010 — I barely know how to use GD. I got my function from another site.
Copy linkTweet thisAlerts:
@narutodude000authorJul 22.2010 — This what I got so far.
[code=php]//the beginning of the function
if ( $source_image_height > $source_image_width )
{
$src_y = $source_image_width;
$src_x = $source_image_width;
$x = 0;
$y = ( $source_image_height - $source_image_width ) / 2;
}
else
{
$src_y = $source_image_height;
$src_x = $source_image_height;
$y = 0;
$x = ( $source_image_width - $source_image_height ) / 2;
}

$thumbnail_gd_image = imagecreatetruecolor( 80, 80 );

imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, $x, $y, 80, 80, $src_x, $src_y );
//the rest of the function[/code]


What's the difference between imagecopyresampled() and imagecopyresized()? Can't they both be used to resize? Which one should I use in my script?
Copy linkTweet thisAlerts:
@NogDogJul 23.2010 — Resampled tends to produce a better-looking result, probably at the expense of a bit extra processing.
Copy linkTweet thisAlerts:
@NogDogJul 23.2010 — To use my function in post #4, you'd simply need to do something like:
[code=php]
$sourceImage = imagecreatefromjpeg($filename);
// add some error-checking in case the above fails, then...
$thumbnail = resize($sourceImage, 80, 80, $error);
if($thumbnail == false) {
die($error); // or whatever you want to do if it fails
}
else {
// do whatever you want to do with $thumbnail
}
[/code]
Copy linkTweet thisAlerts:
@narutodude000authorJul 23.2010 — Thanks, I got it working for uploaded images. However, function generate_image_thumbnail( $source_image_path, $thumbnail_image_path ) doesn't work for a URL of an image file. Why is that?
Copy linkTweet thisAlerts:
@narutodude000authorJul 23.2010 — I got it. Here's the full script for anyone else who wants to use it:
[code=php]//Thumbnail

function generate_image_thumbnail( $source_image_path, $thumbnail_image_path )
{
list( $source_image_width, $source_image_height, $source_image_type ) = getimagesize( $source_image_path );

switch ( $source_image_type )
{
case IMAGETYPE_GIF:
$source_gd_image = imagecreatefromgif( $source_image_path );
break;

case IMAGETYPE_JPEG:
$source_gd_image = imagecreatefromjpeg( $source_image_path );
break;

case IMAGETYPE_PNG:
$source_gd_image = imagecreatefrompng( $source_image_path );
break;
}

if ( $source_gd_image === false )
{
return false;
}

$thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
$thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;

$source_aspect_ratio = $source_image_width / $source_image_height;
$thumbnail_aspect_ratio = $thumbnail_image_width / $thumbnail_image_height;

if ( $source_image_height > $source_image_width )
{
$src_h = $source_image_width;
$src_w = $source_image_width;
$x = 0;
$y = ( $source_image_height - $source_image_width ) / 2;
}
else
{
$src_h = $source_image_height;
$src_w = $source_image_height;
$y = 0;
$x = ( $source_image_width - $source_image_height ) / 2;
}

$thumbnail_gd_image = imagecreatetruecolor( 80, 80 );

imagecopyresampled( $thumbnail_gd_image, $source_gd_image, 0, 0, $x, $y, 80, 80, $src_w, $src_h );

imagejpeg( $thumbnail_gd_image, $thumbnail_image_path, 90 );

imagedestroy( $source_gd_image );

imagedestroy( $thumbnail_gd_image );

return true;
}

//--------------------------------
// FILE PROCESSING FUNCTION
//--------------------------------

function process_image_upload( $field )
{
$temp_image_path = $_FILES[ $field ][ 'tmp_name' ];
$temp_image_name = $_FILES[ $field ][ 'name' ];

$num = 2;
while (1) {
if (file_exists("../wp-content/uploads/wp-post-image/" . $temp_image_name)) {
if ($num == 2) {
preg_match('/.[a-zA-Z]{3,4}$/',$temp_image_name,$match);
$extension = $match[0];
}
$temp_image_name = preg_replace('/.[a-zA-Z]{3,4}$/','',$temp_image_name);
if ($num > 2)
$regex = '/'.$num.'$/';
if ($num > 2)
$temp_image_name = preg_replace($regex,'',$temp_image_name);
$temp_image_name = $temp_image_name.$num;
} else {
if ($num > 2)
$temp_image_name = $temp_image_name.$extension;
break;
}
$num++;
}

list( , , $temp_image_type ) = getimagesize( $temp_image_path );

if ( $temp_image_type === NULL )
{
return false;
}

switch ( $temp_image_type )
{
case IMAGETYPE_GIF:
break;

case IMAGETYPE_JPEG:
break;

case IMAGETYPE_PNG:
break;

default:
return false;
}

$uploaded_image_path = UPLOADED_IMAGE_DESTINATION . $temp_image_name;

move_uploaded_file( $temp_image_path, $uploaded_image_path );

$thumbnail_image_path = THUMBNAIL_IMAGE_DESTINATION . preg_replace( '{\.[^\.]+$}', '.jpg', $temp_image_name );

$result = generate_image_thumbnail( $uploaded_image_path, $thumbnail_image_path );

return $result
? array( $uploaded_image_path, $thumbnail_image_path )
: false;
}

//--------------------------------
// END OF FUNCTIONS
//--------------------------------

define( 'THUMBNAIL_IMAGE_MAX_WIDTH', 80 );
define( 'THUMBNAIL_IMAGE_MAX_HEIGHT', 80 );
if ( $_FILES['file']['size'] > 0 ) {
define( 'UPLOADED_IMAGE_DESTINATION', '../wp-content/uploads/wp-post-image/' );
define( 'THUMBNAIL_IMAGE_DESTINATION', '../wp-content/uploads/wp-post-thumbnail/' );

$result = process_image_upload( 'file' );

if ( $result === false )
{
echo '<script type="text/javascript">history.go(-1)</script>';
die;
}
$thumb = preg_replace('/^..//','http://linksku.com/',$result[1]);
}

if ($thumb==''||!$thumb||!isset($thumb)) {
// Gets the image URL
if (preg_match('/[img]http://[^[]+(jpg|jpeg|jpe|jif|gif|png|bmp|tiff|tif)[/img]/i', $content, $matches)) {
$source_image_path = $matches[0];
$source_image_path = preg_replace('/[img]/','',$source_image_path);
$source_image_path = preg_replace('/[/img]/','',$source_image_path);
// Gets the file name
preg_match('//[^/]+.(jpg|jpeg|jpe|jif|gif|png|bmp|tiff|tif)$/',$source_image_path,$matches);
$file_name = $matches[0];
$thumbnail_image_path = '../wp-content/uploads/wp-post-thumbnail'.$file_name;
if ( generate_image_thumbnail( $source_image_path, $thumbnail_image_path ))
$thumb = 'http://linksku.com/wp-content/uploads/wp-post-thumbnail'.$file_name;
}
}[/code]
×

Success!

Help @narutodude000 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...