[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2274
  • Last Modified:

GD Library- Crop and Resize

Hello

I'm trying to set up a script that will generate thumbnails for an image gallery using GD Library.

I'm using the following script, which resizes the image to 100px x 100px. It's working fine however I was hoping someone could help me customize it so that it shrinks the image by 50% then crops the thumbnail from the center.

<?php

//Input file
$file = 'image.jpg';

//Output file
$save = 'new.jpg';

//Get image dimensions
list($width, $height) = getimagesize($file) ;

//Set new Dimensions
$modwidth = 100;
$modheight = 100;

$tn = imagecreatetruecolor($modwidth, $modheight) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;

imagejpeg($tn, $save, 100);

?>
0
Mr_Splash
Asked:
Mr_Splash
1 Solution
 
jasonsbytesCommented:
so wouldn't you just do some math on the $width and $height to get the size reduced by 50% then use the results to resize and crop it.

?
0
 
Mr_SplashAuthor Commented:
That's exactly what I need to do, but I'm very new to PHP and I'm afraid I don't know the syntax.
0
 
hernst42Commented:
See e.g http://www.php.net/manual/en/function.imagecopyresized.php#74084
in the user comments you will find premade function for that which you can use.
0
 
steelseth12Commented:
or this should work

<?php

//Input file
$file = 'image.jpg';

//Output file
$save = 'new.jpg';

//Get image dimensions
list($width, $height) = getimagesize($file) ;

//Set new Dimensions
$modwidth = $width/2;
$modheight = ($modwidth/$width)*$height;

$tn = imagecreatetruecolor(100, 100) ;
$image = imagecreatefromjpeg($file) ;
imagecopyresampled($tn, $image, 0, 0, $modwidth/2, $modheight/2, $modwidth, $modheight, $width, $height) ;

imagejpeg($tn, $save, 100);

?>
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now