Crop images so that they are a certain ratio width to height

I believe it is possible to display images in the browser so that they all have the same ratio of height to width (regardless of the size and aspect ratio of the original images uploaded by the client).

Trouble is, I don’t know how or where to add the code $dimensions->ratio() | Kirby CMS

I currently have this code in custom block snippet. But now none of the images are displaying in the browser.

<div class="guitar-for-sale">
	<?php if($image = $block->guitar_for_sale_photo()->toFile()): ?>
		<img src="<?= $image->ratio(3/4)->url() ?>" alt="">
	<?php endif ?>
</div>

And tried this:

<div class="guitar-for-sale">
	<?php if($image = $block->guitar_for_sale_photo()->toFile()): ?>
		<img src="<?= $image->$ratio(3/4)->url() ?>" alt="">
	<?php endif ?>
</div>

And this, and other combinations

<div class="guitar-for-sale">
	<?php if($image = $block->guitar_for_sale_photo()->toFile()->ratio(3/4)): ?>
		<img src="<?= $image->url() ?>" alt="">
	<?php endif ?>
</div>

You need to use [crop()](https://getkirby.com/docs/reference/objects/cms/file/crop), there is no ratio() method in the Kirby\Cms\File class.

You cannot use methods of an arbitrary class on some other class object, you can learn the details of object oriented programming here: OOP in PHP | Kirby CMS

This page seems to indicate that we can control the ratio of an image $image->ratio() | Kirby CMS ?

As the description says: it RETURNS the dimensions of the given file. It doesn’t do anything with the file.

Oh okay…

Is it possible using the crop ‘method’ to crop using a ratio, rather than hard pixel dimensions?

crop(3/4) and crop(3:4) don’t work

<div class="guitar-for-sale">
	<?php if($image = $block->guitar_for_sale_photo()->toFile()): ?>
		<img src="<?= $image->crop(3/4)->url() ?>" alt="">
	<?php endif ?>
</div>

That would not make sense.

2px by 4px have the same ratio as 200px by 400px. So what would you expect the result of that ratio crop to be?

I’m thinking aloud, so this is very probably complete rubbish…

I was hoping all the images would have the same ratio. Not necessarily the same dimensions.

So if the client uploaded an image 200px by 600px (and I wanted a ratio of 1:2) this image would get cropped to be 200px by 400px. And if the client uploaded an image 1000px by 500px they would get cropped to 250px by 500px.

But would those images then also be displayed at their cropped sizes? So your 200x400 images would be displayed at 200x400, and your 2000x4000 at that exact size?

If they are all displayed the same size, the only thing that would make sense is that they are cropped to the same size.

Yeah, you’re right. I’ve got into a muddle with this. Thanks for helping me think this through!