interrobang

ImageFocusArea

Recommended Posts

Inputfield And Fieldtype ImageFocusArea

requires ProcessWire 2.5.6 or later

This Inputfield makes it possible to select the important part of the image and use this area for different cropping options. This module is not a replacement for the existing Thumbnails module, though depending on your need it probably could replace it in many cases.

I think a more flexible cropping approach than the existing Thumbnails module is useful especially when using the new html <picture> and you don't want the editor to define multiple thumbnails.

Usage

Create a new Inputfield ImageFocusArea and add it to the desired template. Edit a page with this template and add an image to the new field. You will see a link "Add Image Focusarea". Click the link and you will see a popup with a cropping tool similar to the Thumbnails module. Select the important part of the image, click "apply" and save the page.

By default the Field hooks into Pageimage::size and automatically populates the cropping option with percentages of the center of the selected focusarea. You can always override this behaviour by calling $image->size with a different cropping option (e.g. $image->size(100,100,array('cropping'=>'center'))).

The module introduces 3 new cropping options:

  • align: This is the default if you do not override it with another cropping option. When resizing a image the module only adjusts the alignment of the crop. You will get the most zoomed-out result of these options.
  • inside: Only parts inside of the selected area are used in the resulting image. You will get the most zoomed-in result of these options.
  • outside: The resized image will contain the whole selected area. The surrounding imagearea will be used to reach the targetsize. This is also true for upscaling=false. Upscaling will only happen if the source image was smaller then the targetsize.
API usage examples
// here we force the old/usual 'center' mode:
echo "<img src='{$page->image->size(200,200,array('cropping'=>'center'))}' />";

// by default if you did not define a cropping option, the cropping option gets automatically populated
// Both calls will result in the same image:
echo "<img src='{$page->image->size(200,200)}' />";
echo "<img src='{$page->image->size(200,200, array('cropping'=>'align'))}' />";

// the resulting image will be the center area of the selected focusarea 
echo "<img src='{$page->image->size(200,200, array('cropping'=>'inside'))}' />";
// to get an image with exactly the same ratio as the focusarea use width()/height() instead of a size() 
echo "<img src='{$page->image->width(200, array('cropping'=>'inside'))}' />";
echo "<img src='{$page->image->height(200, array('cropping'=>'inside'))}' />";

// the whole selected area will be part of the image, the surrounding imagearea will only be used to reach the targetsize 
echo "<img src='{$page->image->size(200,200, array('cropping'=>'outside'))}' />";
post-560-0-72201200-1414324998_thumb.png

Flexible CSS Background Images

Additionally you can access a new property cssBackgroundPosition, which could be useful for frontend responsive images. The visual result is similar to the cropping='align' mode, but depending on the size and postion of the focusArea and your images source and target size your mileage may vary. This property is intended to be used together with background-size: cover;. It is important that the background-image has the same ratio as the original image!

<style>
.cssimg{
  background-size: cover;
  width:200px; height: 200px;
}
</style>
<div class="cssimg" style="background-position: <?= $image->cssBackgroundPosition ?>; background-image: url(<?= $image->url ?>);  "></div>
Download

https://github.com/phlppschrr/ImageFocusArea

remember, this modules requires ProcessWire 2.5.6 or later

There are still known bugs with upscaling=false, but I am not sure if it is a bug of this module or a ProcessWire bug. (fixed in ProcessWire 2.5.6)

Thanks to Ryan and especially Horst for all the new great API additions for Pageimage und ImageSizer which made this module possible.

This is my first module. If you notice any problems or unexpected behaviour post here or fill an issue on github. I am open to all suggestions. Do you think the cropping option names (align, inside, outside) are descriptive enough? Any better ideas?

--

Edit: Renamed the Module to ImageFocusArea and updated the github link

Edit 2: Reformatted this post and added some additional information.

  • Like 19

Share this post


Link to post
Share on other sites

@interrobang: Great!

I will try to test it in the next days and give some feedback. But because the issue with "upscaling = false" I'm 99% sure this is a bug in imagesizer and not in your module. It is allready filed at GitHub: https://github.com/horst-n/ProcessWire/commit/6640df43212620532bcd7c24c5936823178d3af6

  • Like 2

Share this post


Link to post
Share on other sites

@horst: Thanks for the info and fix. I just tested your fixed ImageSizer, and now everything looks like expected!

@all:
Which module name do you prefer for field? Before putting this to the module directory I will likely rename this module.

  1. ImageFocusrect 
  2. ImageFocusArea
  3. ImageCroppingArea
  4. ImageSoftCrop
  5. FocusImage
  6. anything else?

--

Edit: Thanks for your feedback. I renamed the module to ImageFocusArea

  • Like 1

Share this post


Link to post
Share on other sites

Sounds like a really great module. Will test this out. Thanks.

I would use ImageFocusArea as a module name. 

  • Like 2

Share this post


Link to post
Share on other sites

I just added a new (experimental) property 'cssBackgroundSize' to Pageimage for supporting frontend responsive images without javascript. Should be used together with background-position: cover. In my tests this worked amazingly well. The result is similar to the 'align' mode. 
 

<style>
.cssimg{
  background-size: cover;
}
</style>
<div class="cssimg" style="background-position: <?= $image->cssBackgroundPosition ?>; background-image: url(<?= $image->url ?>); width:200px; height: 200px; "></div>
  • Like 2

Share this post


Link to post
Share on other sites

+1 ImageFocusArea

if you drag the area outside of the modal window it will close the modal. maybe you can handle this?

post-2137-0-69838500-1414345637_thumb.pn

besides that, cool module/idea. looks promising!

  • Like 1

Share this post


Link to post
Share on other sites

@interrobang: I have installed and tested it and I only can say: wow, really lightweight and straight forward! ^-^

  • Like 1

Share this post


Link to post
Share on other sites

great that you fixed it.

when i tried to change the focusarea i think it didn't update the cropping->inside image. is this  a bug or did i miss anything? look at the third image: it has still the old focusarea.

i also had to append ->url to every image in your github (and first post) sample to work

post-2137-0-33213500-1414408594_thumb.pn

Share this post


Link to post
Share on other sites

@BernhardB:

Thanks for testing, but I am not sure whats happening there. Do you use 'upscaling'=>false? There is a know bug when upscaling is disabled in the current PW release. Horst already fixed it in his fork, and the fix should be included in the next dev release. See 2nd post of this thread.

If you don't prohibit upscaling I will try to reproduce whats happening here. 

Share this post


Link to post
Share on other sites

I just pushed some updates to github. I optimized the handling of the 'outside' mode. Before the update I switched the 'outside' mode to 'align' if the focusArea was smaller then the target size, now I try to expand the focusArea on each side.

@BernhardB: Please give the latest version a try, maybe if fixes your issues, too. I could not reproduce the behaviour you described until now. And update your PW to the latest dev, Ryan just merged Horsts fixes to the ImageSizer.

  • Like 1

Share this post


Link to post
Share on other sites

interrobang, this is awesome! Can't wait to try it out. I have needed this so many times and just found workarounds, my site editors are going to be super excited.

  • Like 2

Share this post


Link to post
Share on other sites

I pushed some updates to github. Outside cropping works now if $image->size() is called with height=0 or width=0.

See my first post for updated API examples to get images with the same ratio as the focusarea

Another thing I think I should mention: If you are testing the different cropping options make sure you prevent getting cached versions. In the moment you have to set the 'suffix' option by yourself. Maybe the module should to this automatically?  (Edit: Since version 0.4.0 the suffix option is set internally by the module, I remove the suffix setting from the example code)

btw, I do my testing like this:

<?php
$image = $page->focusimages->eq(0);
$image->removeVariations();
$sizes = array(
        array(400, 400),
        array(400, 300),
        array(400, 200),
        array(400, 100),
        array(300, 100),
        array(200, 100),
        array(100, 100),
        array(100, 200),
        array(100, 300),
        array(100, 400),
);
$croppings = array(
//        'center',
        'align',
        'inside',
        'outside'
);
$upscaling = true;
?>
    <?php foreach ($croppings as $cropping): ?>
        <div class="row">
            <h1>cropping: <?= $cropping ?></h1>
            <?php foreach ($sizes as $size): ?>
                <?php
                $img = $image->size($size[0], $size[1], array('cropping' => $cropping, 'upscaling'=>$upscaling));
                ?>
                <div class="cropping-example">
                    <span class="info">Size: <?= $size[0] ?>×<?= $size[1] ?></span>
                    <img src="<?= $img->url ?>" width="<?= $img->width ?>" height="<?= $img->height ?>"/>
                </div>
            <?php endforeach ?>
        </div>

    <?php endforeach ?>
  • Like 3

Share this post


Link to post
Share on other sites

@interrobang: If I get this right, with Pageimage / Imagesizer you can use the lately (2.4.? but before 2.5.0) introduced images option "forceNew" to tell Pageimage::size to always create this desired variation new:

$image->size($width, $height, array('forceNew'=>true))

No need to call $image->removeVariations(); anymore!

If you are speaking about something different here, - sorry, I'm a bit in a hurry and haven't read carefully or twice. :)

---

IMO, the suffix should be added internally by your module as with your example above.

And what is if the user want to set an individual suffix?

Well, this could be added to the default suffix from your module by simply concatenate together with a "-":

// somewhere in your module, after you have selected one out of "inside, outside, align, center":
$suffix .= isset($options["suffix"]) ? '-' . $options["suffix"] : '';    // $options is the options
  • Like 1

Share this post


Link to post
Share on other sites

Thanks Horst, but forceNew won't help if you are testing all the different cropping options at once, because at least some of the image variant urls would be the same.

Thanks for the suggestion to add the suffix internally in my module. I will push a update to github later today. I was not sure if this should be up to the developer or not. If I see it right, currently PageImage::size adjusts filename for cropping settings, all other options are not reflected in the filename.

Share this post


Link to post
Share on other sites

I pushed some updates to github:

  • Toggling Grid Mode works now
  • In Grid mode you see only a icon on the thumb to edit the focusArea
  • You no longer have to set a suffix by yourself, this is automatically done in the module
  • Updated version to 0.4.0
  • Like 1

Share this post


Link to post
Share on other sites

Hi interrobang

This is great stuff - really appreciated and I am certain I will use this. 

One thing: I've just downloaded v 0.4 but the Grid Mode still doesn't work for me.

Many thanks

Nik

Share this post


Link to post
Share on other sites

Hi again

I've noticed a couple of further small glitches to your most helpful module.

Transparent PNG's are flattened (with black replacing transparent areas). When no focus area is set, then pngs are output correctly.

When I try to use a standard $image->size($x,$y,array('cropping'=>'false')), without this module this used to return an uncropped image that fitted within the area $x, $y. However, this now returns a cropped image under some circumstances. This is even happening on images that have no focus area set.

Many thanks

Nik

Share this post


Link to post
Share on other sites

Thanks for testing my module. Unfortunately I have urgent client work to do in the moment, but I hope I can do some fixes for this module next week.

Share this post


Link to post
Share on other sites

Thanks interrobang

I have to say that for my needs, this method of controlling image cropping is the most useful and flexible I have come across.

Keep up the good work.

Regards

Nik 

Share this post


Link to post
Share on other sites

Hi again...

I am about to go live with a website using your module - but not the dev version that has the schema changes.

I'm happy with the way it is currently working, but wanted to understand what is better in the dev version. It isn't a simple upgrade if all your previous crops are lost when you uninstall the old module. If I were to upgrade, I guess I would have to find a way to save the crop data first, then re-import it after the new installation - assuming the data is in the same format.

Can you cast any light on this.

Thanks again

Regards

Nik

Share this post


Link to post
Share on other sites

There are probably some bugfixes in the dev version which I don't remember anymore, but the main difference is you can now setup multiple focusareas. These additional focusareas can be defined with a optional width and height which will be used as a default size.

Sorry, all of this is still undocumented and there will probably be some api changes to the module in the future, so I didn't post it here.

If the old version is working fine for you just keep using it, and if you want to update to the dev version you can also change the schema in mysql by hand. You just have to change the schema of the focus row to "text" (old schema was varchar(255)

Hope this helps..

If anyone else here wonders where to find my current dev version and wants to play around with it: 

https://github.com/phlppschrr/ImageFocusArea/tree/thumbnails

But be warned, the api is not fixed yet, and I am thinking about a major refactoring.

Share this post


Link to post
Share on other sites

Many thanks...

Well the old version works just fine... and not pre-defining output sizes but regions of interest gives a lot more flexibility than the other options (imho).

I'll be v careful to test any future upgrade.

Thanks for your help

Nik

Share this post


Link to post
Share on other sites

Hello,

I always get the following message:

Warning: strpos() expects parameter 1 to be string, array given in /home/.sites/.......web/wire/core/Pageimage.php on line 312

Just to clearify: It works as expected and I have turned on the debug mode - so I can see the message, but I dont understand what exactly could be the problem.

This is the code in Pageimage.php starting with line 312

	if(strpos($options['cropping'], 'x') === 0 && preg_match('/^x(\d+)[yx](\d+)/', $options['cropping'], $matches)) {
			$options['cropping'] = true; 
			$options['cropExtra'] = array((int) $matches[1], (int) $matches[2], $width, $height); 
			$crop = '';
		} else {
			$crop = ImageSizer::croppingValueStr($options['cropping']);
		}

Best regards

Share this post


Link to post
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


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By BitPoet
      So I stumbled over the request to allow limiting templates to be used only once under every parent page in this thread
      and found that this would actually come in handy (also in a site I've built).
      The code can be found on github and soon in the module repo.
      After installation, you'll find a new checkbox "Only once per parent" in the family tab when editing a template.

    • By Robin S
      Password Generator
      Adds a password generator to InputfieldPassword.

       
      Usage
      Install the Password Generator module.
      Now any InputfieldPassword has a password generation feature. The settings for the generator are taken automatically from the settings* of the password field.
      *Settings not supported by the generator:
      Complexify: but generated passwords should still satisfy complexify settings in the recommended range. Banned words: but the generated passwords are random strings so actual words are unlikely to occur.  
      https://modules.processwire.com/modules/password-generator/
      https://github.com/Toutouwai/PasswordGenerator
    • By Robin S
      If you've ever needed to insert links to a large number of files within CKEditor you may have found that the standard PW link modal is a somewhat slow way to do it.
      This module provides a quicker way to insert links to files on the page being edited. You can insert a link to an individual file, or insert an unordered list of links to all files on the page with a single click.
      CKEditor Link Files
      Adds a menu to CKEditor to allow the quick insertion of links to files on the page being edited.

      Features
      Hover a menu item to see the "Description" of the corresponding file (if present). Click a menu item to insert a link to the corresponding file at the current cursor position. The filename is used as the link text. If you Alt-click a menu item the file description is used as the link text (with fallback to filename if no description entered). If text is currently selected in the editor then the selected text is used as the link text. Click "* Insert links to all files *" to insert an unordered list of links to all files on the page. Also works with the Alt-click option. Menu is built via AJAX so newly uploaded files are included in the menu without the page needing to be saved. However, descriptions are not available for newly uploaded files until the page is saved. Installation
      Install the CKEditor Link Files module.
      For any CKEditor field where you want the "Insert link to file" dropdown menu to appear in the CKEditor toolbar, visit the field settings and add "LinkFilesMenu" to the "CKEditor Toolbar" settings field.
       
      http://modules.processwire.com/modules/cke-link-files/
      https://github.com/Toutouwai/CkeLinkFiles
    • By matjazp
      A module for managing files and folders. Supports creating, opening (e.g. viewing, playing, editing), renaming, moving, copying, deleting and searching for files. You can also view and change (not supported on Windows) file and directory permissions. 
      https://github.com/matjazpotocnik/ProcessFileManager

      The author of FileManager component is (c) 2006 - 2018 Gerd Tentler, http://www.gerd-tentler.de/tools/filemanager/. I modified it to work with ProcessWire as a module. Please see license files on usage in commercial projects!
    • By Robin S
      An inputfield for displaying markup editable via CKEditor.
      The module is intended for use with the Form Builder module. Allows blocks of static text to be included within a form, which can be edited in the form settings using CKEditor.
      Usage
      Install the Markup CKEditor module.
      In the Form Builder module settings, add "MarkupCKEditor" to "Inputfield types to use with FormBuilder".
      In your form settings, add a new field of type "Markup CKEditor". Enter the text you want to show in this field using "Markup Text" on the "Details" tab.
      Screenshots


       
      http://modules.processwire.com/modules/inputfield-markup-ckeditor/
      https://github.com/Toutouwai/InputfieldMarkupCKEditor