Reputation: 1041
I have the below image which I'd like to crop, so all the black areas are removed and the thumb returned. The thumb must be 130px (width) by 155px (height).
How can I crop it using PHP's GD library? (Imagick library isn't an option).
If there is something I can improve in my question, please let me know.
EDIT
I've used imagecopyresized() function as suggested by @Martijn, with the following code
imagecopyresized(
imagecreatetruecolor(130,155) ,
imagecreatefromjpeg($src_image) ,
0,
0,
0,
0,
130,
155,
260 ,
310
)
What i'm getting is this result
What am I doing wrong?
Upvotes: 1
Views: 1069
Reputation: 16103
This can be hard to do for a library, as the black may differ in size, and the part of the image you may want is not always the same.
I suggest jCrop (yes, the site is very minimal), which allows you to select a part of the image. If it can be done by hand, this is a very easy method. I use this in my company CMS', our customers never need explanation on how it works, very natural :)
If that is not an option, you can try imagecopyresampled()
:
imagecopyresampled(
$dst_image , // the thumb you want to place it on
$src_image , // the image to crop it from
0, // place left of thumb
0, // place top of thumb
0, // start from left of input image
0, // start from top of input image
130, // destination width
155, // destination height
$src_w , // the width of the image without the black
$src_h // the height of the image without the black
)
If you dont have a fixed size for the image on the black canvas, you could write a function to find the offset. You can do this by taking the first line of pixels, and find the first black pixel, and check if there are (lets say) 10min black pixels after that.
This can be sensative, you can increase the scouting area to test if the black is also in the lines below.
Upvotes: 3