Jump to content

CroppableImage


horst

Recommended Posts

is it possible to select the cropped images from my CKeditor image select popup?

That's a great question and actually, would be very useful.

Without using Croppable Image, Ryan introduced a 'native' image crop recently which will allow you to save a version of an image. You can most likely drop that version into CK editor.

It's one of the latter Dev versions I believe.

Link to comment
Share on other sites

CroppableImages and its mother "Thumbnails" are not intended for use in RTEs. But since PW version 2.5.19 Ryan has introduced cropping, rotating, cloning of images in RTEs. It isn't fully implemented yet, (or I must have missed some updates :) ), but is still very good working already.

see: https://processwire.com/blog/posts/new-image-editing-features-2.5.19/

Link to comment
Share on other sites

I have tried the new dev branch, with all the crop and sizing magic. It's pretty flexible, and fast, and easy for some one who knows how to edit images. The concern I'm getting from my client is they don't trust their editors to size their images correctly, to remember the pixel dimensions for a medium sized portrait for example. (anything can be fixed with enough training though) My client however wants their editors to be able to select from a few preset sizes of images that they can drop into the content area: landscape, portrait, banner, etc. It seems like the new dev-branch of processwire could be rigged to work with some preset sizes, but thats that all requires a level of javascript which is not my strong point. CroppableImages on the other hand seems to have 95% of everything I need just does not have the ability to select the images from the RTE. The new image features in the dev branch also do not let you select images that have already been sized in the image fields. I think allowing users to select the different sizes  of an image would be beneficial for both CroppableImage and the new image management tools created by Ryan. I'll take a crack at it, and see what happens.

Link to comment
Share on other sites

Hi Horst,

I checked the filenames your module creates. My original filename was "testslide.jpg", which was saved as "testslide.-sliderbild.jpg". That looks a little weird to me.

In line 194 of FieldtypeCroppableImage.module I found:

$basename = basename($img->basename, '.' . $img->ext) . ".-$suffix" . "." . $img->ext;

Is there any thought behind the ".-" part of the filename? 

What do you think of cleaning the basename to an alpanumeric string, plus dots and symbols?

A quick and dirty way how I'd save the filename:

$basename = preg_replace('/[^a-z0-9\.]+/', '-', strtolower(basename($img->basename, '.' . $img->ext))) . ".$suffix" . "." . $img->ext;

Thank you.

Link to comment
Share on other sites

Your explanation makes no sense to me actually ...

Ok, my fault.

Basically, the docs say a Crop can be called as follows:

<img src='{$preview->Images->first->getCrop('Blog_Preview_Thumb')->url}'>

but in the case below, the first image doesn't have a Crop applied and the page throws an error.

post-1166-0-90493100-1429892089_thumb.jp

So I have to instruct my editors that in a series of images / array of images, the image with the Crop needs to be first in the list.

Link to comment
Share on other sites

I managed to get cropped images working in CKeditor. Here is the code, in case any one is interested in such a hack. If you know a better way to do this, let em know. It would be cool to dynamically get this list of crop settings (thumb, portrait, etc) from the croppedImage field, but, all in all, this seems to work surprisingly well. 

Using the latest dev branch of processwire: 2.5.27

Copy:  /wire/modules/Process/ProcessPageEditImageSelect/ to /site/modules/ProcessPageEditImageSelect/

Made these changes:

//CHANGES TO ALLOWS IMAGE SIZES FROM CROP IMAGE IN RTE
$acceptedCropImageSets = ['thumb','portrait','landscape','thumb'];
foreach($images as $image){
	list($imgBase,$ext) = explode(".", $image->basename); 
	foreach($acceptedCropImageSets as $set)
	{
		$cropedImagePath = wire('config')->paths->files."{$page->id}/{$imgBase}.-{$set}.{$ext}";
		if(file_exists($cropedImagePath))
		{
			$images->add($cropedImagePath);
		}
	}
	$cropImagesGlobSearch = wire('config')->paths->files."{$page->id}/{$imgBase}.-thumb.{$ext}";
}
//CROP IMAGE CHANGES - END

foreach($images as $image) {
	$numImages++;
	$key = $page->id . ',' . $image->basename;  // page_id,basename for repeater support
	$allImages[$key] = $image; 
}
  • Like 1
Link to comment
Share on other sites

$basename = basename($img->basename, '.' . $img->ext) . ".-$suffix" . "." . $img->ext;
Is there any thought behind the ".-" part of the filename?

Hi Kent,

yes indeed, there were some thoughts behind this. :)

The naming scheme for images in PW core has changed somewhere between PW 2.4 and 2.5, but finally and fully functional it is implemented since 2.5.11, if I remember right. The naming scheme is:

// original image name looks like
basename . ext

// all variation descriptions are appended to basename, introduced by a . (dot)
basename . {variation description} . ext

// variation descriptions start with sizes, if present
basename . {WxH} . ext
basename . 0x100 . ext
basename . 80x80 . ext

// sizes can be followed by cropsettings, if present
basename . {WxH}{cropsetting} . ext
basename . 80x80p30x40 . ext
basename . 80x80nw . ext

// resized variations also can have suffixes, introduced by a - (minus sign)
basename . 80x80 - soft . ext
basename . 80x80 - medium . ext
basename . 80x80 - strong . ext
basename . 80x80nw - soft . ext

// variations also can have ONLY suffixes, without a resize part
basename . - suffix . ext

The goal with this was and is: the core pageimage class only should (be able to) handle the cleaning of variations, regardless if variations were created by the core imagesizer or by any third party image module. And the authors of third party image modules should not be made responsible for that. The only thing they have to do is to follow the naming scheme.

There are also possibilities that image variations are passed through a chain of manipulations from different modules, e.g. Cropimage -> coresizer || pia -> pim, what results in a much more weird looking filename. But there never will be an image variation stay orphaned when an original image gets deleted. This is even valid if you have variations created by third party modules where the module is uninstalled already!

So, if you have suggestions to the naming scheme, please first do a check if the above requirements can be fullfilled with them. :)

(see: https://github.com/ryancramerdesign/ProcessWire/blob/dev/wire/core/Pageimage.php#L607)

Link to comment
Share on other sites

  • 3 weeks later...

i'm trying to get a list of valid crop images for the current page so that when I encode some pages in JSON using the JsonPages module the images will have the cropImage image URL's associated with the JSON payload as well as the standard image URL.  

//from the JsonPages module
include('../CroppableImage/classes/CroppableImageCropSettings.class');
$cropSettings = new CroppableImageCropSettings();
$cropSettings->getCropSettingsForTemplate($page->template);
print_r($cropSettings);

result: 

CroppableImageCropSettings Object
(
    [items] => Array
        (
        )

    [names] => Array
        (
        )

    [invalidLines] => Array
        (
        )

    [templateNames] => Array
        (
        )

    [duplicates] => Array
        (
        )

)

My test has a CroppableImage field, with a single thumbnail crop variation.  

It could also be nice to build a function into the $image or the module for getting field names, what do you think?. 

UPDATE:

I got it working this way, by modifying the fieldType for CropImage .

$this->addHook('Pageimage::getCropSettings', $this, 'getCropSettings');

//....

public function getCropSettings(HookEvent $event) {
    $inputFieldInstance = $this->_getInputFieldInstance($event);
    $cropSettings = new CroppableImageCropSettings($inputFieldInstance->cropSetting);           
    $settings =  $cropSettings->getCropSettingsForTemplate($event->object->page->template);
    $event->return = $settings;
    return true;
}
//...
$settings = $image->getGropSettings();

Is this a good place to put this function?

update again: 
A function returns all the cropImages with the crop name would probably the must useful to other people.
$images = $image->getcrops();? //returns all the crop image variations "portrait, landscape, etc." and add a variable to the image object. $image->cropname...or something like that. If that feature would be good, ill be happy to submit it to the project. I have not worked on any open source projects before, so forgive me if I'm being awkward in how i'm going about trying to contribute, and communicate about it. 
 

Link to comment
Share on other sites

In 2.6, one of my Croppable image fields won't accept any updates to it's Crop Settings.

Services-Feature,500,300,services-detail

Updating either the name or the allowed template above has no effect. I downloaded the error log and enabled debug mode and there's no explanation.

is this a known bug with 2.6?

Link to comment
Share on other sites

update again: 

A function returns all the cropImages with the crop name would probably the must useful to other people.

$images = $image->getcrops();? //returns all the crop image variations "portrait, landscape, etc." and add a variable to the image object. $image->cropname...or something like that. If that feature would be good, ill be happy to submit it to the project. I have not worked on any open source projects before, so forgive me if I'm being awkward in how i'm going about trying to contribute, and communicate about it. 

The first part of your idea is practicable, the second one not. At least I don't want to add properties to pageimage from a croppableimage cropsettimgs field. For example if someone calls his thumb "crop", it collides with existing pageimage property from new core. Also it has potential that properties from (other) third party modules collides with those properties. I'm not 100% sure, but tend more to no then yes.

Best way to contributing is to send pull requests to Github. :)

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

Just to let you know, I noticed that the # Variations link, which Ryan introduced a short while ago is missing with CroppableImage module.

I mean the link which show up in the images field list view after the name and size of the image. When clicked it shows all available variations.

Or is there a reason for the link not to be present?

Cheers

Link to comment
Share on other sites

  • 1 month later...
  • 3 weeks later...

I'm having a slight issue on the lastest PW build 2.6.13. I can create a crop but it won't display on the front end.

The same here with 2.6.15 build. $image->getCrop('productcover')  returns null even with the cropped images on the frontend. 

Name and settings for the field is productcover,988,741

Link to comment
Share on other sites

Hello again,

I tracked down the problem on dev branch. Not sure if this is normal or something related to another module but this fixed the frontend problem.

I realized that $inputFieldInstance check on the FieldtypeCroppableImage > getCrop  always returns null on frontend with the multiple image field.

I checked and changed the _getInputFieldInstance method as below. Only change is the $image->pagefile === $pagefiles check part.

I also sent a pull request from github. I hope it's the right fix.

public function _getInputFieldInstance(HookEvent $event) {

        $field = null; // where we'll keep the field we're looking for
        $image = $event->object;
        $page = $image->page;
        $action = $event->arguments[0];

        // find all fields of type FieldtypeImage that are part of the page we're using
        // or regular image fields with InputfieldImage inputfield assigned
        $imageFields = array();
        foreach($page->fields as $f) {
            if ($f->type instanceof FieldtypeCroppableImage || ($f->inputfieldClass && $f->inputfieldClass == 'InputfieldCroppableImage')) {
                $imageFields[] = $f;
            }
        }


        // loop through to find the one we're looking for
        foreach($imageFields as $imageField) {

            // good to get unformatted in case it's a single image field,
            // because it'll still be an array rather than 1 image
            $pagefiles = $page->getUnformatted($imageField->name);          // TODO: name to lowercase 

            $pagefilesFirst = $image->pagefiles->first();


            // if the image's pagefiles property matches the one with the
            // field we're looking at, we have a match. save in $field
            foreach($pagefiles as $pageImageFile) {
                if($pagefilesFirst === $pageImageFile) {

                $field = $imageField->getInputfield($page);
                break;
                }
            }

            //This is commented, not working on dev branch 2.6.15
            /*
            if ($image->pagefiles === $pagefiles) {
                $field = $imageField->getInputfield($page);
                break;
            }
            */
        }

        if ($field) {
            //$event->return = $out;
            return $field;
        }

        return null;
    }
  • Like 2
Link to comment
Share on other sites

where do i define these settings?

in your sites config.php you can set them like below.


$config->imageSizerOptions = array(
    'upscaling' => true, // upscale if necessary to reach target size?
    'cropping' => true, // crop if necessary to reach target size?
    'autoRotation' => true, // automatically correct orientation?
    'sharpening' => 'none', // sharpening: none | soft | medium | strong
    'quality' => 100, // quality: 1-100 where higher is better but bigger
    'hidpiQuality' => 60, // Same as above quality setting, but specific to hidpi images
    'defaultGamma' => -1, // defaultGamma: 0.5 to 4.0 or -1 to disable gamma correction (default=2.0)
);

  • Like 2
Link to comment
Share on other sites

hi bora, thanks for your answer. so i can only set those settings globally? is there no way to set upscaling for "crop1" to true whereas upscaling for "crop2" would be set to false?

As stated in the doc, you can use it when viewing but like:

$image = $page->images->first()->getCrop('portrait', "height=400, sharpening=medium, quality=85");

Not sure if it will be sufficient for your needs.

Link to comment
Share on other sites

thanks. unfortunately not...

for example if you want to have a crop "slider" it would be great to NOT allow upscaling as it would lead to bad quality images on your site's frontpage slideshow. but you could have for example a "facebook" crop that automatically creates a facebook image that will fill up maximum size of your facebook posting. can't think of a better example at the moment. maybe i'll switch it globally to false in my case :)

Link to comment
Share on other sites

thanks. unfortunately not...

for example if you want to have a crop "slider" it would be great to NOT allow upscaling as it would lead to bad quality images on your site's frontpage slideshow. but you could have for example a "facebook" crop that automatically creates a facebook image that will fill up maximum size of your facebook posting. can't think of a better example at the moment. maybe i'll switch it globally to false in my case :)

Yes, I think setting upscaling to false by default is a good idea and whenever necessary you can do it by css anyway.

Link to comment
Share on other sites

  • 3 weeks later...

Have a problem with this module...since i'm switched from local to life server...

PW 2.6.19 all uptodate

No default crop is created...this is really not that good since i can't really uninstall it or switch image handling.. don't have a clue where to start debug or change something on this.... :frantics:

help is very appreciated regards mr-fan

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Similar Content

    • By monollonom
      (once again I was surprised to see a work of mine pop up in the newsletter, this time without even listing the module on PW modules website 😅. Thx @teppo !)
      FieldtypeQRCode
      Github: https://github.com/romaincazier/FieldtypeQRCode
      Modules directory: https://processwire.com/modules/fieldtype-qrcode/
      A simple fieldtype generating a QR Code from the public URL of the page, and more.
      Using the PHP library QR Code Generator by Kazuhiko Arase.

      Options
      In the field’s Details tab you can change between .gif or .svg formats. If you select .svg you will have the option to directly output the markup instead of a base64 image. SVG is the default.
      You can also change what is used to generate the QR code and even have several sources. The accepted sources (separated by a comma) are: httpUrl, editUrl, or the name of any text/URL/file/image field.
      If LanguageSupport is installed the compatible sources (httpUrl, text field, ...) will return as many QR codes as there are languages. Note however that when outputting on the front-end, only the languages visible to the user will be generated.
      Formatting
      Unformatted value
      When using $page->getUnformatted("qrcode_field") it returns an array with the following structure:
      [ [ "label" => string, // label used in the admin "qr" => string, // the qrcode image "source" => string, // the source, as defined in the configuration "text" => string // and the text used to generate the qrcode ], ... ] Formatted value
      The formatted value is an <img>/<svg> (or several right next to each other). There is no other markup.
      Should you need the same markup as in the admin you could use:
      $field = $fields->get("qrcode_field"); $field->type->markupValue($page, $field, $page->getUnformatted("qrcode_field")); But it’s a bit cumbersome, plus you need to import the FieldtypeQRCode's css/js. Best is to make your own markup using the unformatted value.
      Static QR code generator
      You can call FieldtypeQRCode::generateQRCode to generate any QR code you want. Its arguments are:
      string $text bool $svg Generate the QR code as svg instead of gif ? (default=true) bool $markup If svg, output its markup instead of a base64 ? (default=false) Hooks
      Please have a look at the source code for more details about the hookable functions.
      Examples
      $wire->addHookAfter("FieldtypeQRCode::getQRText", function($event) { $page = $event->arguments("page"); $event->return = $page->title; // or could be: $event->return = "Your custom text"; }) $wire->addHookAfter("FieldtypeQRCode::generateQRCodes", function($event) { $qrcodes = $event->return; // keep everything except the QR codes generated from editUrl foreach($qrcodes as $key => &$qrcode) { if($qrcode["source"] === "editUrl") { unset($qrcodes[$key]); } } unset($qrcode); $event->return = $qrcodes; })
    • By Sebi
      AppApiFile adds the /file endpoint to the AppApi routes definition. Makes it possible to query files via the api. 
      This module relies on the base module AppApi, which must be installed before AppApiFile can do its work.
      Features
      You can access all files that are uploaded at any ProcessWire page. Call api/file/route/in/pagetree?file=test.jpg to access a page via its route in the page tree. Alternatively you can call api/file/4242?file=test.jpg (e.g.,) to access a page by its id. The module will make sure that the page is accessible by the active user.
      The GET-param "file" defines the basename of the file which you want to get.
      The following GET-params (optional) can be used to manipulate an image:
      width height maxwidth maxheight cropX cropY Use GET-Param format=base64 to receive the file in base64 format.
    • By MarkE
      This fieldtype and inputfield bundle was built for storing measurement values within a field, rendering them in a variety of formats and converting them to other units or otherwise modifying them via the API.
      The API consists of a number of predefined functions, some of which include...
      render() for rendering the measurement object, valueAs() for converting the value to another unit value, convertTo() for converting the whole measurement object to different units, and add() and subtract() for for modifying the stored value by the value (converted as required) in another measurement. In the admin the inputfield includes a checkbox (which can be optionally disabled) for converting values on page save. For an example if a value was typed in as centimeters, the unit was changed to metres, and the page saved with this checkbox selected, said value would be automatically converted so that e.g. 170 cm becomes 1.7 m.

      A simple length field using Fieldtype Measurement and Inputfield Measurement.
      Combination units (e.g. feet and inches) are also supported.
      Please note that this module is 'proof of concept' at the moment - there are limited units available and quite a lot of code tidying to do. More units will be added shortly.
      See the GitHub at https://github.com/MetaTunes/FieldtypeMeasurement for full details and updates.
    • By tcnet
      File Manager for ProcessWire is a module to manager files and folders from the CMS backend. It supports creating, deleting, renaming, packing, unpacking, uploading, downloading and editing of files and folders. The integrated code editor ACE supports highlighting of all common programming languages.
      https://github.com/techcnet/ProcessFileManager

      Warning
      This module is probably the most powerful module. You might destroy your processwire installation if you don't exactly know what you doing. Be careful and use it at your own risk!
      ACE code editor
      This module uses ACE code editor available from: https://github.com/ajaxorg/ace

      Dragscroll
      This module uses the JavaScript dragscroll available from: http://github.com/asvd/dragscroll. Dragscroll adds the ability to drag the table horizontally with the mouse pointer.
      PHP File Manager
      This module uses a modified version of PHP File Manager available from: https://github.com/alexantr/filemanager
       
    • By tcnet
      This module implements the website live chat service from tawk.to. Actually the module doesn't have to do much. It just need to inserted a few lines of JavaScript just before the closing body tag </body> on each side. However, the module offers additional options to display the widget only on certain pages.
      Create an account
      Visit https://www.tawk.to and create an account. It's free! At some point you will reach a page where you can copy the required JavaScript-code.

      Open the module settings and paste the JavaScript-code into the field as shown below. Click "Submit" and that's all.

      Open the module settings
      The settings for this module are located int the menu Modules=>Configure=>LiveChatTawkTo.

       
×
×
  • Create New...