Jump to content
Hardoman

Admin hook, image upload, watermark, PIM

Recommended Posts

Hello community,

we have a website running version 3.0.118. The owner would like to have a watermark merged to the images, that are being uploaded in the CKEditor as a requirement.
Image upload besides the CKEditor within galleries and single images works as a charm already. We also use croppable image 3 there. (PIM2)

To realize this requirement, I thought of using a hook in the admin area. So, I read a lot in our forums and tested this by adding a hook into the ready.php file.

$this->addHookAfter('InputfieldFile::fileAdded',function(HookEvent$event){
wire('log')->save('test','Image upload works');
...

The log entry is being created correctly. But when I try to use the pim/watermark-function like in a template, he cannot find the watermark-image anymore. Furthermore, when I try to get the page-id, it does not seem to be accessible, because the application does not seem to know how to reference it, or I dont know the right way to do so…

So my questions are:
 

  • Is this the right attempt at all or will there be another, better workaround?
  • It seems, I cannot access the page object (of the content page) within this scope or file but I would need it to save the processed image inside the right files/id folder
  • Would it be better to place the hook into the admin-template? (or admin.php)
     

Thanks for any hints in advance. 🙂

Share this post


Link to post
Share on other sites

You are on the right track. See also here:

Are you using tracy debugger? It can help a lot, eg using bd('hook fired'); will show you what's going on in the tracy bar (or using firelogger fl() can also be helpful.

Share this post


Link to post
Share on other sites
15 minutes ago, Hardoman said:

But when I try to use the pim/watermark-function like in a template, he cannot find the watermark-image anymore.

How do you try to get this image?

15 minutes ago, Hardoman said:

Would it be better to place the hook into the admin-template? (or admin.php)

Doesn't really matter 🙂 

Share this post


Link to post
Share on other sites
5 hours ago, Hardoman said:

So my questions are:
 

  • Is this the right attempt at all or will there be another, better workaround?
  • It seems, I cannot access the page object (of the content page) within this scope or file but I would need it to save the processed image inside the right files/id folder
  • Would it be better to place the hook into the admin-template? (or admin.php)

Hi @Hardoman

I post you a code example below that works for me since ages and also with recent PW versions. It includes watermarking too!

It is called in a custom module and the event is >before "InputfieldFile::fileAdded" <, but you can call it in ready.php too.

Hopefully it is of help for you. Otherwise please ask further. :)

    public function importImage($event) {

        $inputfield = $event->object;                      // handle to the image field
        if(!$inputfield instanceof InputfieldImage) {      // we need an images field, not a file field
            return;                                        // early return
        }

        if(version_compare(wire('config')->version, '2.8.0', '<')) {
            $p = $inputfield->value['page'];               // get the page, PW < 2.8
        } else {
            $p = $inputfield->attributes['value']->page;   // get the page, PW >= 2.8 | 3.0 (or only from 3.0.17+ ??)
        }

        if('images' != $inputfield->name) return;          // we assume a field with name: images
        if('album' != $p->template) return;                // don't do it on other pages than archive album

        $image = $event->argumentsByName('pagefile');      // get the image



        // prebuild variations
            // AdminThumb
            $image->height(260);

            // AlbumThumbnail
            $portrait = $image->height > $image->width;
            $w = 228;
            if($portrait) {
                $w1 = intval($w);
                $h1 = intval(($w1 / 3 * 4) + 38);
            } else {
                $w1 = intval($w);
                $h1 = intval(($w1 / 3 * 2));
            }
            $image->crop("width=$w1, height=$h1");

            // Slick-Slideshow
            $wmPng = $this->pages->get('id=13967')->getUnformatted('watermark')->first()->width(403);
            // sharpening added, quality from 80 to 90
                $master = $image->contain('width=1000, height=700, quality=100, sharpening=none');
                $master = $master->pim2Load('full', false)->watermarkLogo($wmPng)->setQuality(100)->setUpscaling(true)->setSharpening('none')->pimSave();
                $sizeArray = array(array(448, 336), array(678, 506), array(908, 676));
                foreach($sizeArray as $sizes) {
                    $master->size($sizes[0], $sizes[1], array('upscaling'=>false, 'cropping'=>false, 'quality'=>90, 'sharpening'=>'soft'));
                }
            // sharpening added, quality from 80 to 90
        // prebuild variations



        // check / import IPTC data
            $additionalInfo = array();
            $info = @getimagesize($image->filename, $additionalInfo);
            if($info !== false && is_array($additionalInfo) && isset($additionalInfo['APP13'])) {
                $iptc = iptcparse($additionalInfo["APP13"]);
                if(is_array($iptc) && isset($iptc["2#025"]) && is_array($iptc["2#025"]) && count($iptc["2#025"])>0) {
                    $tmp = $iptc["2#025"];
                    $tags = array();
                    foreach($tmp as $k=>$v) {
                        if(empty($v)) continue;
                        $tags[] = jhpTextConversion(trim(strtolower($v)));
                    }
                    $p->images->trackChange('tags');               // prepare page to keep track for changes
                    $image->tags = implode(', ', $tags);
                    $p->save('images');                            // save the page
                }
            }
        // check / import IPTC data

    }

 

  • Like 3

Share this post


Link to post
Share on other sites

Hello Berhard,
hello Horst,

many thanks for your hints and the big code chunk sent by Horst. I'm still testing and will update this comment, when I am done or if there are more questions.

Thank you very much. 🙂

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By toni
      Hi,
      I'm facing a strang problem. In my template I'm setting different sizes for srcset:
      $view->set('images', $page->picture); <img srcset="{$img->size(780,0)->url} 780w, {$img->size(1024,0)->url} 1024w, {$img->size(1440,0)->url} 1440w" src="{$img->url}" class="col__image"> All fine. However, the moment I reorder images in backend the different generated image sizes are broken.
      Does somebody has an idea what could cause it? 
      Version: ProcessWire 3.0.123 
       
      Thanks!
      Toni
    • By nabo
      Hello
      I'm working on a project that use PW as backend CMS. PW serves formatted data of each page but the engine simply generates json from pagearray.
      I would like to set one or more variations on images, so I think it would be useful if there were a field to set possible variations... even with overrides!
    • By PawelGIX
      Can I convert uploaded images to PNG, GIF, BMP -> JPEG?
      Is there any function in the API that I can change the file type?
    • By Robin S
      Repeater Images
      Adds options to modify Repeater fields to make them convenient for "page-per-image" usage. Using a page-per-image approach allows for additional fields to be associated with each image, to record things such as photographer, date, license, links, etc.
      When Repeater Images is enabled for a Repeater field the module changes the appearance of the Repeater inputfield to be similar (but not identical) to an Images field. The collapsed view shows a thumbnail for each Repeater item, and items can be expanded for field editing.
      Screencast

      Installation
      Install the Repeater Images module.
      Setup
      Create an image field to use in the Repeater field. Recommended settings for the image field are "Maximum files allowed" set to 1 and "Formatted value" set to "Single item (null if empty)". Create a Repeater field. Add the image field to the Repeater. If you want additional fields in the Repeater create and add these also. Repeater Images configuration
      Tick the "Activate Repeater Images for this Repeater field" checkbox. In the "Image field within Repeater" dropdown select the single image field. You must save the Repeater field settings to see any newly added Image fields in the dropdown. Adjust the image thumbnail height if you want (unlike the core Images field there is no slider to change thumbnail height within Page Edit). Note: the depth option for Repeater fields is not compatible with the Repeater Images module.
      Image uploads feature
      There is a checkbox to activate image uploads. This feature allows users to quickly and easily add images to the Repeater Images field by uploading them to an adjacent "upload" field.
      To use this feature you must add the image field selected in the Repeater Images config to the template of the page containing the Repeater Images field - immediately above or below the Repeater Images field would be a good position.
      It's recommended to set the label for this field in template context to "Upload images" or similar, and set the visibility of the field to "Closed" so that it takes up less room when it's not being used. Note that when you drag images to a closed Images field it will automatically open. You don't need to worry about the "Maximum files allowed" setting because the Repeater Images module overrides this for the upload field.
      New Repeater items will be created from the images uploaded to the upload field when the page is saved. The user can add descriptions and tags to the images while they are still in the upload field and these will be retained in the Repeater items. Images are automatically deleted from the upload field when the page is saved.
      Tips
      The "Use accordion mode?" option in the Repeater field settings is useful for keeping the inputfield compact, with only one image item open for editing at a time. The "Repeater item labels" setting determines what is shown in the thumbnail overlay on hover. Example for an image field named "image": {image.basename} ({image.width}x{image.height})  
      https://github.com/Toutouwai/RepeaterImages
      https://modules.processwire.com/modules/repeater-images/
    • By VeiJari
      Hello forum!
      I've yet again stumbled on a head-scratching situation. We have enabled the option on our articles template and events template that it skips the title adding part and goes straight to the form. This is what our customer wants. So when you add a new article or event it automatically names it temporary to "article-0000000" and same with event. Now the problem is that obviously after saving the form we want to change to page url or "name" to the title, like it's normally. 
      Now here's the code for the hook:
      wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
        $page = $hook->arguments(0);
        $newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
        wire()->log->message($page->name);
        $page->setAndSave('name', $newUrl);
      });
      I get the correct page and the name and path changes when I log them, but when I try to save it. It just loads and then I get: 
      Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) This happens in sanitizer.php
      and then another error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0
       
      What is happening? Am I not suppose to use sanitizer in this way? When we made a temporary page object in out other hook, the sanitizer worked perfectly.
      Thanks for the help!
×
×
  • Create New...