Image Object of file in assets

hi,
i’m using lingonberry template and i want to add a feature to display a default image, if there is no cover image selected on a specific page template.

the snippet for the coverimage looks like this:

<?php if($image = $item->coverimage()->toFile()) : ?>
<div class="featured-media">
  <a href="<?= $item->url() ?>">
    <img src="<?= $image->resize(766, null, 85)->url() ?>" rel="bookmark" title="<?= $item->title()->html() ?>"<?php e($image->alt()->isNotEmpty(), ' alt="' . $image->alt()->html() . '"') ?>>
    <?php if($image->caption()->isNotEmpty()) : ?>
    <div class="media-caption-container">
      <p class="media-caption">
        <?= $image->caption()->html() ?>
      </p>
    </div>
    <?php endif ?>
  </a>
</div>
<?php endif ?>

My Problem: when i want to load a default image via:

<?php
if(!$image = $item->coverimage()->toFile())  {
$image = kirby()->roots()->assets() . '/images/defaults/traildefault.jpg' ;
}
?>

i just add the string of the imagefile location to the variable $image and i can’t use things like $image->resize(766, null, 85)->url()

as far as i understand, the problem is, that $image = $item->coverimage()->toFile() generates an object, that is not the same as a string of path to file.
so, i think i need to generate such an object of the “external” image, like it is done with the image of the field.

how to do so?

thx in advance

1 Like

To get an image object from an asset file you can try this (untested, but from this post):

<?php $image = new Asset('assets/path/to/default.jpg') ?>

hi,
thx a lot.
I just gave it a try and get error Call to undefined method Asset::alt()
on this line:

<img src="<?= $image->resize(766, null, 85)->url() ?>" rel="bookmark" title="<?= $item->title()->html() ?>"<?php e($image->alt()->isNotEmpty(), ' alt="' . $image->alt()->html() . '"') ?>>

This happens because Assets don‘t have a meta .txt file where additional file field content can be stored. The same will happen with $image->caption().

I would try something like this …

<div class="featured-media">
  <a href="<?= $item->url() ?>">
    <?php if($image = $item->coverimage()->toFile()) : ?>
      <img src="<?= $image->resize(766, null, 85)->url() ?>" rel="bookmark" title="<?= $item->title()->html() ?>"<?php e($image->alt()->isNotEmpty(), ' alt="' . $image->alt()->html() . '"') ?>>
      <!-- ... and so on -->
    <?php else: ?>
      <!-- load image from assets and add alt and caption text on your own -->
    <?php endif; ?>
  </a>
</div>

maybe i can work with that. thx a lot.

the question is just a start of editing this snippet. i want to do many things with the image. for example overlaying a watermark. (already got a solution on this)

it seems i found a better solution. i created a new page at site-root which will hold all images i want to call from other pages.

like this:
$image = page('defaultimages')->image('traildefault.jpg');

2 Likes