Cropping images

I have a website with a hero image on most pages, defined in the page template. This image needs to have a set aspect ratio (2 wide 1 high). The client will be uploading all sorts of image sizes / aspect ratios. How can I get Kirby to crop images to 2:1 aspect ratio?

Here’s my template code:

<?php if ($page->hero_image()->isNotEmpty()): ?>
	<div class="hero-image">
		<?php if ($moondust = $page->hero_image()->toFile()): ?>
			<img src="<?= $moondust->url() ?>" alt="<?= $moondust->alt() ?>">
		<?php endif ?>
	</div>
<?php endif ?>

And here’s code from this page $file->crop() | Kirby CMS

if($image = $page->image()):

    // crop by height as well
    echo $image->crop(1600, 800);

endif;

But I don’t understand how to add this to what I’ve got?

Probably this would do what you’re asking for:

<?php if ($moondust = $page->hero_image()->toFile()): ?>
	<div class="hero-image">
		<?= $moondust->crop(1600, 800) ?>
	</div>
<?php endif ?>

Or if you don’t want to hardcode the size, but just crop to whatever the largest possible 2:1 aspect ratio is (might end up really big if the user uploads images directly taken from a reflex, I wouldn’t do this):

<?php if ($moondust = $page->hero_image()->toFile()): ?>
	<?php 
	$ratio = 2/1;
	$size = $moondust->ratio() > $ratio
		? [$moondust->height() * $ratio, $moondust->height()] 
		: [$moondust->width(), $moondust->width() / $ratio];
	?>
	<div class="hero-image">
		<?= $moondust->crop(...$size) ?>
	</div>
<?php endif ?>
1 Like

Hey, that’s amazing! Thanks.

I’ve removed the following

<?php if ($page->hero_image()->isNotEmpty()): ?>
<?php endif ?>

and to my surprise pages with no set hero-image still work. I thought if the hero-image was missing/empty it would break the PHP and I’d get the PHP error page. Any ideas why it still works?

Yes, it’s not necessary to have two if statements, if the field is empty, $page->fieldname()->toFile() will return null and hence not be true.

thanks