Remove extension from image

Hey,

i want to remove the extension from my images.

Why?
I convert my images with the “kirby webp” plugin to webp and now i want to add them to my page. And i dont know what filetypoe the original upload will be

  <picture>
    <source srcset="<?= $image->url() ?>" type="image/webp">
    <source srcset="<?= $image->url() ?>" type="image/jpeg">
    <source srcset="<?= $image->url() ?>" type="image/png">
    <img src="<?= $image->resize(25)->url() ?>" alt="Alt Text!" class="lazyload">
  </picture>

the problem is that the url() looks like this:
media/pages/testpage/fd870d9a58-1613134009/compressed.png

now i want to remove the extension from the url and add the images like this

  <picture>
    <source srcset="<?= $image->url()->removeExtensionSmh() ?>webp" type="image/webp">
    <source srcset="<?= $image->url()->removeExtensionSmh() ?>jpeg" type="image/jpeg">
    <source srcset="<?= $image->url()->removeExtensionSmh() ?>png" type="image/png">
    <img src="<?= $image->resize(25)->url() ?>"  class="lazyload">
  </picture>

Any idea?

Best
Marvin :slight_smile:

You can use Str::replace() to chop off the extension from the end.

solved it in this way now:

  <?php $imageWithoutEx = pathinfo($image->url()) ?>
  <picture>
    <source data-srcset=" <?= $imageWithoutEx['dirname'] .  "/" . $image->name() . ".webp" ?>" type="image/webp">
    <source data-srcset="<?= $imageWithoutEx['dirname'] .  "/" . $image->name() . ".jpg" ?>" type="image/jpg">
    <source data-srcset="<?= $imageWithoutEx['dirname'] .  "/" . $image->name() . ".png" ?>" type="image/png">
    <img alt="<?= $image->alt() ?>" title="<?= $image->title() ?>" width="1920" height="1080" src="<?= $image->resize(25)->url() ?>" data-src="<?= $image->url() ?>" class="lazyload">
  </picture>

Is your way better? and if yes, why?

No, totally fine.

1 Like

Additional question:

i want to check if the file exists.

  <?php $imageWithoutEx = pathinfo($image->url()) ?>
  <?php $imageWebp =  $imageWithoutEx['dirname'] .  "/" . $image->name() . ".webp" ?>

  <?php if ($imageExists = $imageWebp->toFile()->exists()) : ?>
  <?php endif ?>

but this doesnt work that way.
any idea how i could check it?

if ( $webp = $page->image($image->name() . '.webp') ) {
  // do stuff
}