flokosiol / kirby-focus

Better image cropping for Kirby CMS
184 stars 14 forks source link

Presets also with focusSrcset()? #49

Closed hariom147 closed 4 years ago

hariom147 commented 4 years ago

Hi @flokosiol - first of all thanks for providing this plugin - Is there also a way to use presets with focusSrcset(), analog to:

<?= $image->focusPreset('square') ?>
<?= $image->focusPreset('rectangle') ?>

? I need to ask, because it's not mentioned in the docs...

flokosiol commented 4 years ago

Hi @lucadorata I'm sorry, but this is not possible at the moment. But the following idea might work (untested!):

In your config.php as described here.

<?php
return [
    'debug'  => true,
    'mySrcsetPresetConfig' => [
        '800w' => [
            'width' => 800,
            'height' => 800,
        ],
        '1400w' => [
            'width' => 1400,
            'height' => 1400,
        ]
    ]
];

In your template, snippet, whatever …

<?php $myFocusSrcsetPreset = option('mySrcsetPresetConfig'); ?>
<img 
  src="<?= $image->focusCrop(1000, 1000)->url() ?>"
  srcset="<?= $image->focusSrcset($myFocusSrcsetPreset); ?>"
>

Would be awesome if you could drop me a line if this works for you. Good luck 😉

hariom147 commented 4 years ago

Hi @flokosiol, just want to let you know, that your suggestion worked like a charm. I was able to access the thumbs options already configured in config.php. I used this code:

      $preset = option('thumbs.presets');
      $srcset = option('thumbs.srcsets');
      $pV = $preset[$data->imagecrop()->value()];
      $sV = $srcset[$data->imagecrop()->value()];

      $items = $data->slides()->toStructure();
      foreach ($items as $item):

      if ($item->image()->isNotEmpty()):
        if ($data->imagecrop() != "default") {
          // cropped image
          $image = $item->image()->toFile()->focusCrop($pV['width'], $pV['height'], ['quality' => $pV['quality']]);
          $imagesrcset = $item->image()->toFile()->focusSrcset($sV);
jonasfeige commented 4 years ago

I need a similar functionality very often, or rather a simpler way to build a srcset, so I built my own version of the focusSrcset function. Maybe it can be helpful for someone, love this plugin and find it a littler easier to use this way.

It has some defaults based on my own needs and the Tailwind breakpoints. But you can also pass a custom width and height for the base (smallest) image. It also accepts an array of breakpoints with the expected screen width and a ratio that refers to how much bigger the iteration should be than the base (smallest) image.

fcs-srcset

$image->fcsSrcset()

$image->fcsSrcset(['width' => 500, 'height' => 400]);

$image->fcsSrcset(['breakpoints' => 
[
'width' => 1024,
'ratio' => 1
],
[
'width' => 1440,
'ratio' => 1.2
]
]);
flokosiol commented 4 years ago

Thanks for sharing!