I am using imagine library to create thumbnails for images. It is as simple as this.
$size = new \Imagine\Image\Box(240, 180);
$imagine->open($source_path)->thumbnail($size, 'inset')->save($target_path);
the library provides two modes : inset and outbound. in inset mode the image is resized down but it does not fill the thumbnail size. So I need to pad it to fill the target size. Is there an easy way to do this using library functions ?
You have to crop your image if you don't want to "scale" thumbnails to fit. For cropping, you have to find exact starting points and it requires a little bit effort.
Writing a custom method to find exact cropping point, resize and return the new image is good idea. Imagine is really good library, it provides all methods we need.
Steps to follow:
Pseudo code:
function resizeToFit( $targetWidth, $targetHeight, $sourceFilename )
{
// Box is Imagine Box instance
// Point is Imagine Point instance
$target = new Box($targetWidth, $targetHeight );
$originalImage = imagine->open( $sourceFilename );
$orgSize = $originalImage->getSize();
if ($orgSize->width > $orgSize->height) {
// Landscaped.. We need to crop image by horizontally
$w = $orgSize->width * ( $target->height / $orgSize->height );
$h = $target->height;
$cropBy = new Point( ( max ( $w - $target->width, 0 ) ) / 2, 0);
} else {
// Portrait..
$w = $target->width; // Use target box's width and crop vertically
$h = $orgSize->height * ( $target->width / $orgSize->width );
$cropBy = new Point( 0, ( max( $h - $target->height , 0 ) ) / 2);
}
$tempBox = Box($w, $h);
$img = $originalImage->thumbnail($tempBox, ImageInterface::THUMBNAIL_OUTBOUND);
// Here is the magic..
return $img->crop($cropBy, $target); // Return "ready to save" final image instance
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With