Jump to content

Page Image Manipulator | API for 1 & 2


horst

Recommended Posts

That wasn't my intention at all :) We have all fallen victim to this one - several times!

I don't ever remember to do it, but it is why it is recommended to do:

f("Y"==$on){

With it reversed like that, if you forget the second equals sign, it will throw an error, rather than assigning the value!

No, I definitely needed to have my nose rubbed in it if I couldn't see my mistake from Soma's comment. ;)

Good tip on reversing the comparison, I will try to make that my habit going forward!

Now as for Page Image Manipulator, I still see it recreating the images if I don't check for the image and skip it manually. :huh: 

(Latest code is in my edited previous post)

Link to comment
Share on other sites

  • 2 weeks later...

There's a weird thing going on or I must do something silly. (dev 2.5.18)

/**
 * Options need to be set, if not I see the below error:
 * Error: Exception: Error when trying to save the MemoryImage: we have no Targetfilename! ...
 * (weird I guess)
 *
 */

$options = array('outputFormat' => 'jpg');
 
// Call PIM
$pim = $image->pimLoad("bright", true)->setOptions($options)->contrast(100)->brightness(100)->pimSave();
 
/**
 * There's no prefix in the filename of the image (should be 'bright' I guess), 
 * Now the original image is overwritten every time, after 3 or 4 page loads the image will be blank.  
 *
 */
 
/**
 * Setting setTargetFilename() in the PIM call and PIM works as expected.
 *
 */

$watermark = $page->rootParent->png;
$assets = str_replace($image->ext, '', $image->filename) . "video.150x112.jpg";
$pim = $image->size(150, 112)->pimLoad("video", true)->setTargetFilename($assets)->watermarkLogo($watermark, 'center', 0)->pimSave();
$image = "<img src='$pim->url' />";
---

I've spend a few hours to debug, but can't find any clue.

Edited by Martijn Geerts
  • Like 1
Link to comment
Share on other sites

@Martijn: I have tested it with PW 2.5.19 from this afternoon (14:00). I cannot replicate all of what you have reported.

WHen I take a basename.png and use your code example from above I get the right output:

// original   =>  variation
basename.png  =>  pim_bright_basename.jpg  

// URL  
/site/assets/files/1/pim_bright_basename.jpg

BUT it recreates it everytime new, also if I set the second param to false:

$options = array('outputFormat' => 'jpg');
 
// Call PIM
$pim = $image->pimLoad("bright", FALSE)->setOptions($options)->contrast(100)->brightness(100)->pimSave();

This is a bug or inconveniance by design, but If you call it this way it works as expected, without recreating it everytime:

$options = array('outputFormat' => 'jpg');
 
// Call PIM
$pim = $image->pimLoad("bright", FALSE, $options)->contrast(100)->brightness(100)->pimSave();
Link to comment
Share on other sites

  • 1 month later...

I found out that the modue is not set to singular in the module header:

    static public function getModuleInfo() {
        return array(
            'title'      => 'Page Image Manipulator',
            'version'    => 14,
            'summary'    => 'This module provide basic Imagemanipulations for Pageimages and Imagefiles',
            'author'     => 'horst',
            'href'       => 'http://mods.pw/5E',
            'singular'   => false,
            'autoload'   => true
        );
    }

But because of this init gets called again and again:

    public function init() {
        $this->addHook('Pageimage::pimLoad', $this, 'getPageImageManipulator');
        $this->addHook('Pageimage::isVariation', $this, 'HookIsVariationPim');
    }

Funny enough it gets called with every call to a "pimLoad" initiated by a hook. Thus the hooks mulitply causing the module to crash (timeout exceeded) after 7 to 10 images beeing processed in a row within a single page.

I set the module to singular and everything seems to work fine.

  • Like 3
Link to comment
Share on other sites

:-[ , many thanks! This is fixed now in the Github repo.

Ok great. I was not 100% sure if setting it to "single" would be the perfect solution as I'm still not too familiar with the module architecture.

But it seems reasonable to me, and if it also seems reasonable to you then its fine. At least it works fine for me even when scaling 50 images in a row for a automatically generated slideshow.

Thanks for the plugin, it produces way better results than the standard image plugin in terms of quality.

BTW: I needed centred scaled down images that are not cropped and keep their proportions. Thus I had to add the following code:

function galleryimage($image) {
   if(($image->width / $image->height) > (600 / 400))
       return $image->pimLoad("gallery")->width(600)->canvas(600,400)->pimSave();
   else
       $img = $image->pimLoad("gallery")->height(400)->canvas(600,400)->pimSave();
}

Maybe you could add an option to scale that allows to keep proportions that way as this is something others might need too.

Actually this task was the reason for me to choose pim as this is not done correctly by the standard scaling algorithm, it seems to produce images that are not centred when you add an image that has the correct width but not the correct height. So when calling this with an image of e.g. 600x300 i would get a reulting image where all the added vertical canvas is on the bottom or if i remeber correctly it just returned the orignal image even though it was of the wrong size.

return $image->size(600, 400, array( 'upscaling' => true, 'cropping' => false, 'quality' => 97 ));

But thats something for the core module developers maybe.

  • Like 2
Link to comment
Share on other sites

Thanks for the plugin, it produces way better results than the standard image plugin in terms of quality.

.

Hhm, hard to believe. It uses the same functions and params as you can use with the core ImageSizer.

.

.

.

BTW: I needed centred scaled down images that are not cropped and keep their proportions. Thus I had to add the following code:

function galleryimage($image) {
   if(($image->width / $image->height) > (600 / 400))
       return $image->pimLoad("gallery")->width(600)->canvas(600,400)->pimSave();
   else
       $img = $image->pimLoad("gallery")->height(400)->canvas(600,400)->pimSave();
}
Maybe you could add an option to scale that allows to keep proportions that way as this is something others might need too.

.

The PiM is a bit outdated. The function you suggested is missing, I know. But I have no time at the moment to work on this.

.

.

.

Actually this task was the reason for me to choose pim as this is not done correctly by the standard scaling algorithm, it seems to produce images that are not centred when you add an image that has the correct width but not the correct height. So when calling this with an image of e.g. 600x300 i would get a reulting image where all the added vertical canvas is on the bottom or if i remeber correctly it just returned the orignal image even though it was of the wrong size.

return $image->size(600, 400, array( 'upscaling' => true, 'cropping' => false, 'quality' => 97 ));
But thats something for the core module developers maybe.

.

The core ImageSizer does not support canvas. But there is one other API-level ImageTool available: Pia. With it you can use $image->contain(), what reduces both sizes (width and height) to fit into given boundaries.

.

:)

Link to comment
Share on other sites

Hi Horst

I just went to update this via the updater on a site and got this error:

Error: Cannot redeclare PageEditFieldPermissionConfig() (previously declared in /home/justright/public_html/site/modules/PageEditFieldPermission/PageEditFieldPermissionConfig.php:8) (line 8 of /home/justright/public_html/site/modules/PageEditFieldPermission/PageEditFieldPermissionConfig.php) 

Which produced an server internal error for the entire site.

I have removed the page edit field permissions module (removed the folder) and that solved it. But why does updating your module break this other one?

On another PW site I tried uninstalling yours instead and the same thing happened. Removing the PIM folder didn't solve it.

Link to comment
Share on other sites

Hey Joss - I think the issue is more about refreshing the modules cache in general which probably happens when you update another module. That error with PageEditFieldPermissionConfig is actually a bit painful - if you upgraded PW to latest dev before upgrading the module it becomes quite difficult to get rid of that error because you can't actually upgrade the module to the latest version that fixes it. You might need to manually uninstall it, then reinstall - at least that was my experience.

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

I am very new to PW and PHP so please bear with me: I am probably making fundamental errors...

I have pages generated by a  template called postcard: each contain a jpg image which I am trying to watermark.  I am using PW Intermediate profile.

I have PageImageManipulator installed, I've created an imagefield called 'watermarkfield' and created a template called 'tools' with only Title and watermarkfield. I have then created a child page of Home called 'tools' using the tools template and have included in it a transparent png file called watermark.png in the watermarkfield.  I have saved the tools page as 'hidden'.

The content of the template postcard.php is:

<?php

// postcard.php template file
// See README.txt for more information

// Primary content is the page's body copy
$content = $page->body;

$png = $pages->get('/tools/')->watermarkfield;
foreach($images as $image) {
    $watermarked_image = $image->pimLoad('tw', true)->width(500)->watermarkLogo($png, 'southwest', 0)->pimSave();
    echo "<img src='{$watermarked_image->url}' />";
}

I am getting the following error on the produced pages:

Notice: Undefined variable: images in /var/www/vhosts/the-limes.com/httpdocs/site/templates/postcard.php on line 10
Warning: Invalid argument supplied for foreach() in /var/www/vhosts/the-limes.com/httpdocs/site/templates/postcard.php on line 10

Please can someone put me right?

Link to comment
Share on other sites

Hi @grumpy,

It looks to me that you have done nearly everything right. The only thing you left out is to populate $images in your code. I think you simply forgot

$images = $page->images;

, assumed that your current $page has an images field that is called "images".

But you also can ommit this extra line and change your code in line 10 to be:

foreach($page->images as $image) {
Link to comment
Share on other sites

Thank you horst.  I did option 2 (see above) and it went wrong big time!

Fatal error: Exception: Cannot read the pngAlphaImageFile! (in /var/www/vhosts/the-limes.com/httpdocs/site/modules/PageImageManipulator/ImageManipulator.class.php line 1652) #0 /var/www/vhosts/the-limes.com/httpdocs/site/templates/postcard.php(11): ImageManipulator->watermarkLogo(Object(Pageimages), 'southwest', 0) #1 /var/www/vhosts/the-limes.com/httpdocs/wire/core/TemplateFile.php(169): require('/var/www/vhosts...') #2 [internal function]: TemplateFile->___render() #3 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(366): call_user_func_array(Array, Array) #4 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(321): Wire->runHooks('render', Array) #5 /var/www/vhosts/the-limes.com/httpdocs/wire/modules/PageRender.module(356): Wire->__call('render', Array) #6 /var/www/vhosts/the-limes.com/httpdocs/wire/modules/PageRender.module(356): TemplateFile->render() #7 [internal function]: PageRender->___renderPage(Object(HookEvent)) #8 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(366): call_user_func_a in /var/www/vhosts/the-limes.com/httpdocs/index.php on line 252
Error: Exception: Cannot read the pngAlphaImageFile! (in /var/www/vhosts/the-limes.com/httpdocs/site/modules/PageImageManipulator/ImageManipulator.class.php line 1652)

#0 /var/www/vhosts/the-limes.com/httpdocs/site/templates/postcard.php(11): ImageManipulator->watermarkLogo(Object(Pageimages), 'southwest', 0)
#1 /var/www/vhosts/the-limes.com/httpdocs/wire/core/TemplateFile.php(169): require('/var/www/vhosts...')
#2 [internal function]: TemplateFile->___render()
#3 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(366): call_user_func_array(Array, Array)
#4 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(321): Wire->runHooks('render', Array)
#5 /var/www/vhosts/the-limes.com/httpdocs/wire/modules/PageRender.module(356): Wire->__call('render', Array)
#6 /var/www/vhosts/the-limes.com/httpdocs/wire/modules/PageRender.module(356): TemplateFile->render()
#7 [internal function]: PageRender->___renderPage(Object(HookEvent))
#8 /var/www/vhosts/the-limes.com/httpdocs/wire/core/Wire.php(366): call_user_func_a

Link to comment
Share on other sites

In case it helps, to give the fatal error etc. (see above) my amended postcard template read (I've since reverted it to the original error):

<?php

// postcard.php template file
// See README.txt for more information

// Primary content is the page's body copy
$content = $page->body;

$png = $pages->get('/tools/')->watermarkfield;
foreach($page->images as $image) {
    $watermarked_image = $image->pimLoad('tw', true)->width(500)->watermarkLogo($png, 'southwest', 0)->pimSave();
    echo "<img src='{$watermarked_image->url}' />";
}

Link to comment
Share on other sites

This error says that there is something wrong with your PNG file.

Please check on the tools template if the watermarkfield is set for a single image or for multiple images. If it is setup for multiple images, please correct it.

You can also check in your template if you got an imageobject:

$png = $pages->get('/tools/')->watermarkfield;

if (empty($png)) {
    // uhm, something went wrong!
    ... stop with further execution
}
Edited by horst
Link to comment
Share on other sites

You were absolutely right about that.  I did it and finally I have an image with a watermark.  Thank you very much for your help.  That's the good news... BUT.....

please look at:

http://www.the-limes.com/postcards/chalfont-st-peter/chalfont-st-peter-001/

We have made new images at the head of  the document (including watermarking the green png button which didn't want watermarking) and the image which did need to be watermarked does not have one.

If I store the postcard images (without watermark) in a protected directory on my website is PIM able to watermark them as they are called for by the postcard template?

Link to comment
Share on other sites

You need to apply the watermarking to the right image(field).

If you don't want oversized, watermarked images in your header menu, simply do not apply it there.

Look through your template code and find the right position, not where you have the header menu but where you output the postcard image.

Also be aware that currently, when trying out things, you may get displayed cached images also when altering the code. To force new creation of Pim images put as a second argument to pimLoad() a boolean true, BUT don't forget to remove it, once you have finished your code!

Link to comment
Share on other sites

  • 2 months later...
  • 2 months later...

Thank you for this Great Module !

I stuck with variations. Without resize image by using ProcessWire api variations not working. If i use ProcessWire sizing api with pim2Load function there are many files (no need them).

What i want to do :

1- Make a duplicate from original and keep original

2- Apply watermark to duplicated image

3- If result is fine for resize size, use this image for resizing (OR) resize from original and apply watermark, but don't make duplicates (for better watermark result)

4- See variations on admin panel, if i delete all images or specified image, delete all variations. (Deletion not working with below codes, if i delete image on filesystem i can see all watermarked images)

// Also i tried with pim2Load('wmi')->stepResize(image->width)->watermarkLogo($wmPath, 'c', '2')->pimSave();
$duplicateAndWatermarkOriginal = $image->pim2Load('wmi')->watermarkLogo($wmPath, 'c', '2')->pimSave();
// Create a small sized 1130x500px
// Also i tried with pim2Load('wmi')->stepResize(1130, 500)->watermarkLogo($wmPath, 'c', '2')->pimSave();
$smallFromDuplicated = $duplicateAndWatermarkOriginal->size(1130, 500);

Watermarked images is working and not regenerating them. Also i added a log message to your class. For check whats happened.

            if('page'==$this->entryItem) {
                $this->message("pageImage setFilename, setOriginal, targetFilename :: {$targetFilename}", Notice::log);
                $pageimage = clone $this->pageimage;
                $pageimage->setFilename($targetFilename);
                $pageimage->setOriginal($this->pageimage);
                return $pageimage;
            }

And i can have logs messages. Sometimes i can see variations count going up (from 2 variations to 4 variations) on list view of images but when i click variations its going down (from 4 variations to 2 variation) and on the list created images not appear.

Now i am running script like this and variations are working :

// Duplicated from original (same size), and apply watermark (here we have 2 original size without watermark and 1 with watermark)
$dImage = $image->size($image->width)->pim2Load('wmi')->watermarkLogo($wmPath, 'c', '2')->pimSave();
// Create small size from $dImage already watermarked (not have a duplicate  )
$sSizeImage = $dImage->size(1130, 500);
// If i want to create from original again (we have one more duplicate)
$sSizeFromOriginal = $image->size(1130, 500)->pim2Load('wmismall')->watermarkLogo($wmPath, 'c', '2')->pimSave();
Link to comment
Share on other sites

Hi @ukyo,

maybe there are optimization possibilities in your workflow. If you don't mind, I write down some thoughts ?

1) if you don't want send your original (master) image through the browser, (what I highly recommend), upload it with the max quality setting you can. (Speaking on JPEG only here in this regard).

2) try to reduce the image processing steps to a minimum. In your example you first call size with original width. This triggers a complete image manipulation including creation of a diskfile with the exact dimensions of the original image. But with a lower quality (depending of your default settings, maybe: 90). This lesser quality version is then loaded into pim2 and gets watermarked, and again saved with default value for quality. This is repeated once again for the $sSizeImage.

Better would be to A) use quality 100 for all intermediate steps and only save the last one with your desired endquality. I would create one fullsize variation with the watermark logo.

// creates a copy of the original, but with watermark and suffix "wmi"
$wmiImage = $image->pim2Load('wmi')->watermarkLogo($wmPath, 'c', '2')->setQuality(100)->setSharpening('none')->pimSave();

 Now use this wmi image (variation) for your resized versions:

// create an image 1130x500
$sSizeImage1 = $wmiImage->size(1130, 500);

// create an image max width 300 
$sSizeImage2 = $wmiImage->width(300);

// and so on, ...

This way you have the original image plus one fullsize with watermark and one variation for every output image.

Link to comment
Share on other sites

On my side, i tested some methods for add resized or watermarked images to variations for admin panel :
 
If i change your suffix and if i use variation name like ProcessWire (width x height) :
 

// From
$suffix = "-pim2-{$suffix}";

// To
$suffix = ".pim2.{$suffix}";

// And making watermarking by use variation like ProcessWire
// Watermark from original
$dImage = $image->pim2Load("{$image->width}x{$image->height}")->watermarkLogo($wmPath, 'c', '2')->pimSave();

// Create medium size from original with watermark
$mImg = $image->pim2Load("1130x500")->resize(1130, 500)->watermarkLogo($wmPath, 'c', '2')->pimSave();

// Use medium size for resize (will be watermarked making only resize)
$mImg = $mImg->size(750, 300);

Created files on disk :

rh4c5k.jpg

Here created variations :

r88me0.jpg

Original Size Watermarked

2uiu6bc.jpg

Medium Size Watermarked

ndvimt.jpg

I am not displaying original image. Displaying watermarked and sized images. Like this if i delete images from admin panel delete image and variations, clean work. Now the problem is file sizes as you see on my screen shot.

2h6dnxx.jpg

Order : Original Image - Watermarked from Original image - Resized from watermarked original image 

Edited: File sizes screenshot added.

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...

@ukyo: you were right, there was a bug with the naming of variations. With using them from API in templates, it wasn't a big problem, but with trying to use them with the CKeditor it was, because the created name of the variation prevents PW from identifying them as variations, as you said.

I found out that there simply was missing a single dot in front of the suffix string: -pim2-suffix has to be .-pim2-suffix in cases where only the pim works on original images, whereas when pim worked on a variation, everything worked alright.

This is fixed now with version 0.2.7 of pim2.

Link to comment
Share on other sites

Hi Folks,

I hope somebody can help me out with following problem:

After a fresh Install of PW 2.7 i installed the wunderful Module of Horst "PAGE IMAGE MANIPULATOR" .

But I am not able to call the module functions. I Always get the following errormessage. It seems to me
that PW don't know anything of the installed module. But it is installed correctly. 

Horst mentioned , it could be something with accessrights of my file/image - field. But I tried out nearly 
everything to fix the problem. maybe some of you had a same problem.

ErrorMessage:

Error:     Exception: Method Pagefile::pim2Load does not exist or is not
callable in this context (in [...]/⁠html/⁠wire/⁠core/⁠Wire.php line 358)

#0 [internal function]: Wire-⁠>___callUnknown('pim2Load', Array)
#1 [...]/⁠html/⁠wire/⁠core/⁠Wire.php(398): call_user_func_array(Array, Array)
#2 [...]/⁠html/⁠wire/⁠core/⁠Wire.php(333): Wire-⁠>runHooks('callUnknown', Array)
#3 [...]/⁠html/⁠wire/⁠core/⁠Wire.php(337): Wire-⁠>__call('callUnknown', Array)
#4 [...]/⁠html/⁠wire/⁠core/⁠Wire.php(337): Pagefile-⁠>callUnknown('pim2Load',
Array)
#5 [...]/⁠html/⁠site/⁠templates/⁠basic-⁠page.php(18):
Wire-⁠>__call('pim2Load', Array)
#6 [...]/⁠html/⁠site/⁠templates/⁠basic-⁠page.php(18): Pagefile-⁠>pim2Load('test')
#7 [...]/⁠html/⁠site/⁠templates/⁠ho

This error message was shown because you are logged in as a Superuser.
Error has been logged.

The Problem also come up on a local windowsinstall with WAMPP and a Live- Webserver install on linux. 

:-(((

Thanks a lot

Michael

Link to comment
Share on other sites

@ukyo: you were right, there was a bug with the naming of variations. With using them from API in templates, it wasn't a big problem, but with trying to use them with the CKeditor it was, because the created name of the variation prevents PW from identifying them as variations, as you said.

I found out that there simply was missing a single dot in front of the suffix string: -pim2-suffix has to be .-pim2-suffix in cases where only the pim works on original images, whereas when pim worked on a variation, everything worked alright.

This is fixed now with version 0.2.7 of pim2.

I wrote my own module. Because, I have a project need to finish it quickly.

On my side file sizes are important. With your module. if you apply watermark file sizes going up (this is normal but x2 size up, not normal) On the screenshots you can see the results.

If you want have a look to my module here is a link : https://processwire.com/talk/topic/11318-avbimage/

And on attachment you can see my module result  :

post-2064-0-48512500-1447810184_thumb.pn

  • Like 1
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
×
×
  • Create New...