Jump to content

Simple way to get unformatted Pageimage/Pagefile from formatted?


Recommended Posts

I am close to releasing a module that adds hook methods to Pageimage that will calculate the main color and/or a palette of dominant colors in an image.

I've been looking at different options to store/cache this value based on a comparison of the options array used to grab the first calculation, because with some image sizes and precision factors and the number of images the calculation lags more than you would want on a front-facing site. If the data exisits, use it unless the options array passed along is different than the one stored - in which case recalculate.

My initial thought was to store them in the filedata array for the given file, and I can get/pull the item but I cannot save the Pageimage filedata within the hook because the hook runs regardless of whether or not you get the initial images in a formatted or unformatted state.

I can grab the data and save it outside the hook method like so:

$page = $this->wire->pages->get('name=about');
$images = $page->getUnformatted('images');
foreach($images as $image) {
    $palette = $image->palette();
    $maincolor = $image->maincolor();
    $image->save();
}

But this makes the process more cumbersome for developers. I'd rather have the hook method somehow be able to grab the unformatted version of the Pageimage from the Pageimages returned by the 'images' field, merge the filedata colors into the filedata array and save it.

The problem is I can't see how to query an individual image/file within that Pageimages/Pagefiles array.

Link to comment
Share on other sites

Okay I think I found a way - it is circuitous but it seems to work, so I will post it for posterity in case anyone else is trying to mess around with saving similar data in this way...

//This is for use INSIDE a method being added via Pageimage::addHookMethod but Pagefile should work in a similar manner

//Grab the event object.
$f_pageImage = $event->object;

//Grab the page the event object lives on.
$page = $f_pageImage->page;

//Grab the unformatted version of the pageimages array the event object lives in from the field
$u_Images = $page->getUnformatted($f_pageImage->field->name);

//Grab the file inside the unformatted field content array that has the same filename as the original file objects filename
$pageImage = $u_Images->getFile($f_pageImage->basename);

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...