horst

Module
Page Image Manipulator 1

225 posts in this topic

---------------------------------------------------------------------------------------------------------------------------------

  when working with PW version 2.6+, please use Pim2, not Pim!

  read more here  on how to change from the older to the newer version in existing sites

---------------------------------------------------------------------------------------------------------------------------------

PageImage Manipulator

The Page Image Manipulator is a module that let you in a first place do ImageManipulations with your PageImages. - And in a second place there is the possibility to let it work on any imagefile that exists in your servers filesystem, regardless if it is a 'known PW-image'.

The Page Image Manipulator is a Toolbox for Users and Moduledevelopers. It is written to be as close to the Core ImageSizer as possible. Besides the GD-filterfunctions it contains resize, crop, canvas, rotate, flip, sharpen, unsharpMask and 3 watermark methods.



How does it work?
pw_pim_codeexample01.jpg
You can enter the ImageManipulator by calling the method pim2Load(). After that you can chain together how many actions in what ever order you like. If your manipulation is finished, you call pimSave() to write the memory Image into a diskfile. pimSave() returns the PageImage-Object of the new written file so we are able to further use any known PW-image property or method. This way it integrates best into the ProcessWire flow.

The three examples above put out the same visual result: a grayscale image with a width of 240px. Only the filenames will slightly differ.

You have to define a name-prefix that you pass with the pimLoad() method. If the file with that prefix already exists, all operations are skipped and only the desired PageImage-Object gets returned by pimSave(). If you want to force recreation of the file, you can pass as second param a boolean true: pim2Load('myPrefix', true).

You may also want to get rid of all variations at once? Than you can call $pageimage->pim2Load('myPrefix')->removePimVariations()!

A complete list of all methods and actions are at the end of this post.
 
You may also visit the post with tips & examples for users and module developers.


How to Install

  • Download the module
  • Place the module files in /site/modules/PageImageManipulator/
  • In your admin, click Modules > Check for new modules
  • Click "install" for PageImageManipulator
  • Done! There are no configuration settings needed, just install and use it.

Download    (version 0.2.0)

History of origins

http://processwire.com/talk/topic/3278-core-imagemanipulation/


----------------------------------------------------------------------------------------------------------


Page Image Manipulator - Methods

* pimLoad  or  pim2Load, depends on the version you use!

pimLoad($prefix, $param2=optional, $param3=optional)

  • param 1: $prefix - (string) = mandatory!
  • param 2: mixed, $forceRecreation or $options
  • param 3: mixed, $forceRecreation or $options
  • return: pim - (class handle)
  • $options - (array) default is empty, see the next method for a list of valid options!
  • $forceRecreation - (bool) default is false

It check if the desired image variation exists, if not or if forceRecreation is set to true, it prepares all settings to get ready for image manipulation
-------------------------------------------------------------------

* setOptions

setOptions(array $options)

  • param: $options - (array) default is empty
  • return: pim - (class handle)

Takes an array with any number valid options / properties and set them by replacing the class-defaults and / or the global config defaults optionally set in the site/config.php under imageSizerOptions or imageManipulatorOptions.

valid options are:

  • quality = 1 - 100 (integer)
  • upscaling = true | false (boolean)
  • cropping = true | false (boolean)
  • autoRotation =true | false (boolean)
  • sharpening = 'none' | 'soft' | 'medium' | 'strong' (string)
  • bgcolor = (array) css rgb or css rgba, first three values are integer 0-255 and optional 4 value is float 0-1, - default is array(255,255,255,0)
  • thumbnailColorizeCustom = (array) rgb with values for colorize, integer -255 - 255 (this can be used to set a custom color when working together with Thumbnails-Module)
     
  • outputFormat = 'gif' | 'jpg' | 'png' (Attention: outputFormat cannot be specified as global option in $config->imageManipulatorOptions!)

set {singleOption} ($value)
For every valid option there is also a single method that you can call, like setQuality(90), setUpscaling(false), etc.
-------------------------------------------------------------------

* pimSave

pimSave()

  • return: PageImage-Object

If a new image is hold in memory, it saves the current content into a diskfile, according to the settings of filename, imagetype, targetFilename and outputFormat. Returns a PageImage-Object!
-------------------------------------------------------------------

* release

release()

  • return: void (nothing)

if you, for what ever reason, first load image into memory but than do not save it, you should call release() to do the dishes! ;-) If you use pimSave() to leave the ImageManipulator, release() is called automatically.
-------------------------------------------------------------------

* getOptions

getOptions()

  • return: associative array with all final option values

example:

["autoRotation"] bool(true)
["upscaling"] bool(false)
["cropping"] bool(true)
["quality"] int(90)
["sharpening"] string(6) "medium"
["targetFilename"] string(96) "/htdocs/site/assets/files/1124/pim_prefix_filename.jpg"
["outputFormat"] string(3) "jpg"

get {singleOption} ()
For every valid option there is also a single method that you can call, like getQuality(), getUpscaling(), etc. See method setOptions for a list of valid options!
-------------------------------------------------------------------

* getImageInfo

getImageInfo()

  • return: associative array with useful informations of source imagefile

example:

["type"] string(3) "jpg"
["imageType"] int(2)
["mimetype"] string(10) "image/jpeg"
["width"] int(500)
["height"] int(331)
["landscape"] bool(true)
["ratio"] float(1.5105740181269)
["bits"] int(8)
["channels"] int(3)
["colspace"] string(9) "DeviceRGB"

-------------------------------------------------------------------

* getPimVariations

getPimVariations()

  • return: array of Pageimages

Collect all pimVariations of this Pageimage as a Pageimages array of Pageimage objects. All variations created by the core ImageSizer are not included in the collection.

-------------------------------------------------------------------

* removePimVariations

removePimVariations()

  • return: pim - (class handle)

Removes all image variations that was created using the PIM, all variations that are created by the core ImageSizer are left untouched!

-------------------------------------------------------------------

* width

width($dst_width, $sharpen_mode=null)

  • param: $dst_width - (integer)
  • param: $auto_sharpen - (boolean) default is true was deleted with version 0.0.8, - sorry for breaking compatibility
  • param: $sharpen_mode - (string) possible: 'none' | 'soft' | 'medium' | 'strong', default is 'soft'
  • return: pim - (class handle)

Is a call to resize where you prioritize the width, like with pageimage. Additionally, after resizing, an automatic sharpening can be done with one of the three modes.
-------------------------------------------------------------------

* height

height($dst_height, $sharpen_mode=null)

  • param: $dst_height - (integer)
  • param: $auto_sharpen - (boolean) default is true was deleted with version 0.0.8, - sorry for breaking compatibility
  • param: $sharpen_mode - (string) possible: 'none' | 'soft' | 'medium' | 'strong', default is 'soft'
  • return: pim - (class handle)

Is a call to resize where you prioritize the height, like with pageimage. Additionally, after resizing, an automatic sharpening can be done with one of the three modes.
-------------------------------------------------------------------

* resize

resize($dst_width=0, $dst_height=0, $sharpen_mode=null)

  • param: $dst_width - (integer) default is 0
  • param: $dst_height - (integer) default is 0
  • param: $auto_sharpen - (boolean) default is true was deleted with version 0.0.8, - sorry for breaking compatibility
  • param: $sharpen_mode - (string) possible: 'none' | 'soft' | 'medium' | 'strong', default is 'soft'
  • return: pim - (class handle)

Is a call to resize where you have to set width and / or height, like with pageimage size(). Additionally, after resizing, an automatic sharpening can be done with one of the three modes.
-------------------------------------------------------------------

* stepResize

stepResize($dst_width=0, $dst_height=0)

  • param: $dst_width - (integer) default is 0
  • param: $dst_height - (integer) default is 0
  • return: pim - (class handle)

this performs a resizing but with multiple little steps, each step followed by a soft sharpening. That way you can get better result of sharpened images.
-------------------------------------------------------------------

* sharpen

sharpen($mode='soft')

  • param: $mode - (string) possible values 'none' | 'soft'| 'medium'| 'strong'
  • return: pim - (class handle)

Applys sharpening to the current memory image. You can call it with one of the three predefined pattern, or you can pass an array with your own pattern.

-------------------------------------------------------------------

* unsharpMask

unsharpMask($amount, $radius, $threshold)

  • param: $amount - (integer) 0 - 500, default is 100
  • param: $radius - (float) 0.1 - 50, default is 0.5
  • param: $threshold - (integer) 0 - 255, default is 3
  • return: pim - (class handle)

Applys sharpening to the current memory image like the equal named filter in photoshop.

Credit for the used unsharp mask algorithm goes to Torstein Hønsi who has created the function back in 2003.

-------------------------------------------------------------------

* smooth

smooth($level=127)

  • param: $level - (integer) 1 - 255, default is 127
  • return: pim - (class handle)

Smooth is the opposite of sharpen. You can define how strong it should be applied, 1 is low and 255 is strong.
-------------------------------------------------------------------

* blur

blur()

  • return: pim - (class handle)

Blur is like smooth, but cannot called with a value. It seems to be similar like a result of smooth with a value greater than 200.
-------------------------------------------------------------------

* crop

crop($pos_x, $pos_y, $width, $height)

  • param: $pos_x - (integer) start position left
  • param: $pos_y - (integer) start position top
  • param: $width - (integer) horizontal length of desired image part
  • param: $height - (integer) vertical length of desired image part
  • return: pim - (class handle)

This method cut out a part of the memory image.
-------------------------------------------------------------------

* canvas

canvas($width, $height, $bgcolor, $position, $padding)

  • param: $width = mixed, associative array with options or integer, - mandatory!
  • param: $height = integer, - mandatory if $width is integer!
  • param: $bgcolor = array with rgb or rgba, - default is array(255, 255, 255, 0)
  • param: $position = one out of north, northwest, center, etc, - default is center
  • param: $padding = integer as percent of canvas length, - default is 0
  • return: pim - (class handle)

This method creates a canvas according to the given width and height and position the memory image onto it.

You can pass an associative options array as the first and only param. With it you have to set width and height and optionally any other valid param. Or you have to set at least width and height as integers.

Hint: If you want use transparency with rgba and your sourceImage isn't of type PNG, you have to define 'png' as outputFormat with your initially options array or, for example, like this: $image->pimLoad('prefix')->setOutputFormat('png')->canvas(300, 300, array(210,233,238,0.5), 'c', 5)->pimSave()

-------------------------------------------------------------------

* flip

flip($vertical=false)

  • param: $vertical - (boolean) default is false
  • return: pim - (class handle)

This flips the image horizontal by default. (mirroring)
If the boolean param is set to true, it flips the image vertical instead.
-------------------------------------------------------------------

* rotate

rotate($degree, $backgroundColor=127)

  • param: $degree - (integer) valid is -360 0 360
  • param: $backgroundColor - (integer) valid is 0 - 255, default is 127
  • return: pim - (class handle)

This rotates the image. Positive values for degree rotates clockwise, negative values counter clockwise. If you use other values than 90, 180, 270, the additional space gets filled with the defined background color.
-------------------------------------------------------------------

* brightness

brightness($level)

  • param: $level - (integer) -255 0 255
  • return: pim - (class handle)

You can adjust brightness by defining a value between -255 and +255. Zero lets it unchanged, negative values results in darker images and positive values in lighter images.
-------------------------------------------------------------------

* contrast

contrast($level)

  • param: $level - (integer) -255 0 255
  • return: pim - (class handle)

You can adjust contrast by defining a value between -255 and +255. Zero lets it unchanged, negative values results in lesser contrast and positive values in higher contrast.
-------------------------------------------------------------------

* grayscale

grayscale()

  • return: pim - (class handle)

Turns an image into grayscale. Remove all colors.
-------------------------------------------------------------------

* sepia

sepia()

  • return: pim - (class handle)

Turns the memory image into a colorized grayscale image with a predefined rgb-color that is known as "sepia".
-------------------------------------------------------------------

* colorize

colorize($anyColor)

  • param: $anyColor - (array) like css rgb or css rgba - but with values for rgb -255 - +255,  - value for alpha is float 0 - 1, 0 = transparent  1 = opaque
  • return: pim - (class handle)

Here you can adjust each of the RGB colors and optionally the alpha channel. Zero lets the channel unchanged whereas negative values results in lesser / darker parts of that channel and higher values in stronger saturisation of that channel.
-------------------------------------------------------------------

* negate

negate()

  • return: pim - (class handle)

Turns an image into a "negative".
-------------------------------------------------------------------

* pixelate

pixelate($blockSize=3)

  • param: $blockSize - (integer) 1 - ??, default is 3
  • return: pim - (class handle)

This apply the well known PixelLook to the memory image. It is stronger with higher values for blockSize.
-------------------------------------------------------------------

* emboss

emboss()

  • return: pim - (class handle)

This apply the emboss effect to the memory image.
-------------------------------------------------------------------

* edgedetect

edgedetect()

  • return: pim - (class handle)

This apply the edge-detect effect to the memory image.
-------------------------------------------------------------------

* getMemoryImage

getMemoryImage()

  • return: memoryimage - (GD-Resource)

If you want apply something that isn't available with that class, you simply can check out the current memory image and apply your image - voodoo - stuff
-------------------------------------------------------------------

* setMemoryImage

setMemoryImage($memoryImage)

  • param: $memoryImage - (GD-Resource)
  • return: pim - (class handle)

If you are ready with your own image stuff, you can check in the memory image for further use with the class.
-------------------------------------------------------------------

* watermarkLogo

watermarkLogo($pngAlphaImage, $position='center', $padding=2)

  • param: $pngAlphaImage - mixed [systemfilepath or PageImageObject] to/from a PNG with transparency
  • param: $position - (string) is one out of: N, E, S, W, C, NE, SE, SW, NW,
    - or: north, east, south, west, center, northeast, southeast, southwest, northwest
    default is 'center'
  • param: $padding - (integer) 0 - 25, default is 5, padding to the borders in percent of the images length!
  • return: pim - (class handle)

You can pass a transparent image with its filename or as a PageImage to the method. If the watermark is bigger than the destination-image, it gets shrinked to fit into the targetimage. If it is a small watermark image you can define the position of it:

     NW - N - NE
     |    |    |
     W  - C -  E
     |    |    |
     SW - S - SE

 
The easiest and best way I have discovered to apply a big transparency watermark to an image is as follows:
create a square transparent png image of e.g. 2000 x 2000 px, place your mark into the center with enough (percent) of space to the borders. You can see an example here! The $pngAlphaImage get centered and shrinked to fit into the memory image. No hassle with what width and / or height should I use?, how many space for the borders?, etc.
-------------------------------------------------------------------

* watermarkLogoTiled

watermarkLogoTiled($pngAlphaImage)

  • param: $pngAlphaImage - mixed [systemfilepath or PageImageObject] to/from a PNG with transparency
  • return: pim - (class handle)

Here you have to pass a tile png with transparency (e.g. something between 150-300 px?) to your bigger images. It got repeated all over the memory image starting at the top left corner.
-------------------------------------------------------------------

* watermarkText

watermarkText($text, $size=10, $position='center', $padding=2, $opacity=50, $trueTypeFont=null)

  • param: $text - (string) the text that you want to display on the image
  • param: $size - (integer) 1 - 100, unit = points, good value seems to be around 10 to 15
  • param: $position - (string) is one out of: N, E, S, W, C, NE, SE, SW, NW,
    - or: north, east, south, west, center, northeast, southeast, southwest, northwest
    default is 'center'
  • param: $padding - (integer) 0 - 25, default is 2, padding to the borders in percent of the images length!
  • param: $opacity- (integer) 1 - 100, default is 50
  • param: $trueTypeFont - (string) systemfilepath to a TrueTypeFont, default is freesansbold.ttf (is GPL & comes with the module)
  • return: pim - (class handle)

Here you can display (dynamic) text with transparency over the memory image. You have to define your text, and optionally size, position, padding, opacity for it. And if you don't like the default font, freesansbold, you have to point to a TrueTypeFont-File of your choice.
Please have a look to example output: http://processwire.com/talk/topic/4264-release-page-image-manipulator/page-2#entry41989
-------------------------------------------------------------------





PageImage Manipulator - Example Output

pw_screenshot_pim_exampleThumbs.jpg

33 people like this

Share this post


Link to post
Share on other sites

PageImage Manipulator - Tips & Examples


* how to create a PNG with transparency for the watermarkLogo method

If you can use adobe photoshop, you simply may download and install this action: photoshop_action_PW-png-creations.zip

  • create an empty image (transparent, not white or black) of 2000 x 2000 pixel
  • write / paste your text and / or logo in a single color, (e.g. black)
  • when finished with your text you should have one single layer with text on transparent background
  • then click the action PW-png-creations -> 2000px-square-to-smooth and you are done.

Hhm, maybe before saving you want to tweak the global transparency of the image a bit. That one used in the ProcessWire example was set to 75% instead of 100%. Just try out what looks best for you.


-------------------------------------------------------------------

* did you know that you can save to different file formats, regardless of source format?
 
You only have to specify your desired format (gif, jpg, png) with the optionally options array with a key named outputFormat and pass it with your call to pimLoad() or use setOptions() before any other action-method:

// assuming the first image is a jpeg
$img = $page->images->first();

// define outputFormat
$options = array('outputFormat'=>'png');

// apply it together with other actions
$myPng = $img->pimLoad('myPrefix')->setOptions($options)->width(240)->pimSave();

//------------------------------------------------------------------------------------------
// you may also do it as a OneLiner only with the image format conversion 
$myPng = $page->images->eq(0)->pimLoad('myPrefix', array('outputFormat'=>'png'))->pimSave();

// or you can use the setOutputFormat method
$myPng = $page->images->first()->pimLoad('myPrefix')->setOutputFormat('png')->pimSave();

-------------------------------------------------------------------

* (how) can I use the ImageManipulator with other imagefiles than PW-Pageimages?

You can load any imagefile from your servers filesystem into the ImageManipulator with:

$pim = wire('modules')->get('PageImageManipulator')->imLoad($imageFilename);
// or
$pim = $wire->modules->get('PageImageManipulator')->imLoad($imageFilename, $options);

You can directly with the imLoad-method pass specific $options or you can do a separate call to setOptions(). Then you do your desired actions and last but not least you call save()! Most time I think the original passed file gets overwritten with the manipulation result, but you are also able to save to a different name and  / or fileformat. If so, it is useful to get the final (sanitized) filename back after saveing.

$optionalNewFilename = $pim->setOptions($options)->height(360)->flip()->blur()->save();

Also you may call this in one line if you prefer:

if(false!==$wire->modules->get('PageImageManipulator')->imLoad($imageFilename,$options)->height(360)->flip()->blur()->save()) {
    // success !!
}

-------------------------------------------------------------------

* how can I use the PageImageManipulator with my own module/s?

If you build a module that do some image manipulation you can define the PIM as needed dependency in your ModulesInfo method with the key 'requires'. You may also force to install the PIM if it isn't already with the key 'installs':

public static function getModuleInfo() {
    return array(
        // ...
        'requires' => array('PageImageManipulator'),
        'installs' => 'PageImageManipulator',
        // ...
    );
}

detailed infos are here: http://processwire.com/talk/topic/778-module-dependencies/

additionally, if you need to check if a module dependency has a minimum version number, you can do it in your install method like this:

public function ___install() {
    // check that at least the minimum version number is installed
    $needed = '0.0.3';
    $a = wire('modules')->get('PageImageManipulator')->getModuleInfo();
    $actual = preg_replace('/(\d)(?=\d)/', '$1.', str_pad("{$a['version']}", 3, "0", STR_PAD_LEFT));
    if(version_compare($actual, $needed, '<')) {
        throw new WireException(sprintf($this->_(__CLASS__ . " requires PageImageManipulator %s or newer. Please update."), $needed));
        return;
    }
    // ... more code
}


-------------------------------------------------------------------

* global options in site/config.php

You can create a config-array in your site/config.php. If you look into it you will find a config array for the ImageSizer that comes with the PW core

$config->imageSizerOptions = array(
	'autoRotation' => true,
	'sharpening' => 'soft',
	'upscaling' => true,
	'cropping' => true,
	'quality' => 90
);

You can define another array with these keys:

$config->imageManipulatorOptions = array(
	'autoRotation' => true,
	'sharpening' => 'soft',
	'upscaling' => false,
	'cropping' => true,
	'quality' => 90,
	'bgcolor' => array(255,255,255,0),
);

You don't have to specify all of the options. PiM reads the imageSizerOptions and merge them with the imageManipulatorOptions. So if you want to have different values you can specify them in imageManipulatorOptions to override those from imageSizerOptions. Only one option isn't present with the imageSizer: bgcolor. This is only used by the imageManipulator.


-------------------------------------------------------------------

* using PiM together with the awesome Thumbnails Module  (http://mods.pw/1b)


If you use the Thumbnails Module together with PiM, you can set two options in the site/config.php under imageManipulatorOptions:

$config->imageManipulatorOptions = array(
   // ...
	'thumbnailColorizeCustom' => array(40,-35,0),
	'thumbnailCoordsPermanent' => true
);

For the colorize dropdown select you can define the custom color here and with the second param you enable/disable permanent storage of RectangleCoords and params. The coords and params are stored with Thumbnails Module per session, but are lost after the session is closed. If you enable permanent storage these data is written into a custom IPTC field of the original imagefile.


-------------------------------------------------------------------

* some more examples will folow here

 . . .

-------------------------------------------------------------------
 

Edited by horst
20 people like this

Share this post


Link to post
Share on other sites

Horst, finally =)

I've yet to dive into all of that but it looks great at first glance. Thanks for the awesome contribution.

1 person likes this

Share this post


Link to post
Share on other sites

Do you plan to integrate some of Photoshops filters too? :P

Nice module btw, great work!!! ^-^

1 person likes this

Share this post


Link to post
Share on other sites

Nice module btw, great work!!! ^-^

thanks Wanze!

Do you plan to integrate some of Photoshops filters too? :P

Hhm, I think: no!   :P :P

I prefer to use photoshop directly with a wrapper class that uses the COM-technique on Windows ;)

2 people like this

Share this post


Link to post
Share on other sites

@Horst: Oh, so now we can talk? I understood your last post before the above to mean you needed space (content overflowing across various posts) to finish writing IManipulator's tutorial b4 we could start posting :D

Congrats on this great achievement! :)

1 person likes this

Share this post


Link to post
Share on other sites

@Horst: Oh, so now we can talk? I understood your last post before the above to mean you needed space (content overflowing across various posts) to finish writing IManipulator's tutorial b4 we could start posting :D

Congrats on this great achievement! :)

Thanks Kongondo,

- and yes, you (partly) understood right!

At least I want to have a different post for further added examples, you know, the IP.board editor sometimes lost the text structure when there is a lot of text in it.

Share this post


Link to post
Share on other sites

Very impressive module Horst! I look forward to using it. Please post to the modules directory too if possible. Thanks for your great work here. 

2 people like this

Share this post


Link to post
Share on other sites

This is looking very nice. I'm specificly interested in the watermark. Going to give it a try.

1 person likes this

Share this post


Link to post
Share on other sites

I'm probably doing something wrong, because i'm getting an error with trying the watermarkLogo and watermarkLogoTiled

I was thinking the $pngAlphaImage has to be an image object or url so i tried both ways, with out any luck.

$img = $page->images->first();

$wmi = $page->watermark;

$imgsrc = $img->pimLoad('tw',true)->width(240)->watermarkLogoTiled($wmi->url)->pimSave();

echo "<img src='{$imgsrc->url}' /><br />";
 

Can you point out what i'm doing wrong? The error is below:

Error: Exception: Cannot read the pngAlphaImageFile! (in
/Users/user/Sites/www_domains/processwire/htdocs/site/modules/PageImageManipulator/ImageManipulator.class.php
line 1271)
 

Share this post


Link to post
Share on other sites

It looks like that you need a path, not a url. (didn't test it)

See checkDiskfile methode on line 1569

1 person likes this

Share this post


Link to post
Share on other sites

@Martijn a path works fine, i needed to use $wmi->filename instead.

$img = $page->images->first();

$wmi = $page->watermark;

$imgsrc = $img->pimLoad('tw',true)->width(240)->watermarkLogoTiled($wmi->filename)->pimSave();

echo "<img src='{$imgsrc->url}' /><br />";
 

@horst it would be nice to be able to position the watermark image. I have used a small 50×50 px. In phpThumb it is possible to position the watermark image with the following values:

LT - T - RT
L  - C -  R

LB - B - RB

or to have it the ProcessWire way: northwest, north, northeast, west, center, east, southwest, south, southeast
 

2 people like this

Share this post


Link to post
Share on other sites

@horst it would be nice to be able to position the watermark image. I have used a small 50×50 px. In phpThumb it is possible to position the watermark image with the following values:

LT - T - RT

L  - C -  R

LB - B - RB

or to have it the ProcessWire way: northwest, north, northeast, west, center, east, southwest, south, southeast

Hey Raymond, thanks for trying this.

I will add this like the ProcessWire way with 'n' 'north' 'center' 'c' etc, because of consistency with the ImageSizer. It was already on the todo list because I need it for the watermarkText method too, but currently I'm running a bit out of time.

Also I will make the watermark methods accept pageimage and filename for the $pngAlphaImage!

2 people like this

Share this post


Link to post
Share on other sites

Thats great news, looking forward to give it a try when its finished.

Using a pageImage object makes sence when its needed to rescale or in any other way pim modify the watermark in way go.

1 person likes this

Share this post


Link to post
Share on other sites

@Raymond: I have uploaded a new version with the positioning added! Let me know how it works.

@all: there was a little bug (a 0 instaed of a 1) in the module file at Line 81 that has ignored the forceRecreation param.

Please update both files to version 0.0.2 (link is in the first post)

Edit:

@Raymond: Yes you are right, it is really nice to have the watermark image as pageImage too.

I have tried this:

$img = $page->images->first();

$wmi = $page->watermark->pimLoad('wmi')->colorize('red')->pimSave();

$imgsrc = $img->pimLoad('tw',true)->width(180)->grayscale()->watermarkLogo($wmi, 'southeast', 0)->pimSave();

echo "<img src='{$imgsrc->url}' /><br />";

and a grayscale watermark becomes red. Nice! Have not thought about this possibilities before. :)

post-1041-0-31086100-1376592788.png   post-1041-0-48913000-1376592726_thumb.jp

Edited by horst
2 people like this

Share this post


Link to post
Share on other sites

Greetings,

Very excellent work Horst! I have tried this in a sandbox site and cannot wait to integrate it into a live project.

Now, how about preventing clients from uploading photos that ruin our beautiful designs? Maybe a hand that reaches out and stops them from clicking "submit" in certain cases? Or maybe an automatic watermark that stamps "developer not responsible for this image."

But seriously, your work is amazing.

Thanks,

Matthew

2 people like this

Share this post


Link to post
Share on other sites

@horst thanks for these extra features in the watermarkLogo process. One question what does the 0 stand for?

$padding (in percent of the image length), default is 2

(I also have updated the method doc in first post with this) ;)

Share this post


Link to post
Share on other sites

Hhm, I have finalized the third WatermarkMethod: watermarkText()

(and have uploaded the third and (hopefully) last version of the module: http://processwire.com/talk/topic/4264-release-page-image-manipulator/)

But it isn't really what I wanted it to be. It is because GD2 with PHP (at least with version < 5.5.0) doesn't support anti aliasing for transparency! :(

My initially plan was to analyse the source image histogram-data and automaticly set the fontcolor to more lighten or darker. Also I want to have it a bit blurred and transparent. But everytime one define the transparent color for the overlayed textmask, it gets cutted the hard way! (0 = nothing or 1=100%, and nothing in between) :(

I have tried to get a bit around that behave and now it depends on the source images. Sometimes it seems to be possible to use the method, and sometimes it's to ugly!
 

pw_watermarkText_example.jpg

1 person likes this

Share this post


Link to post
Share on other sites

The module is updated to version 0.0.4 and is available in the modules section now: http://mods.pw/5E

There are no other additions planned!

(So there should be some improvements done for a final stable version 1.0: all logging and errorhandling should be made ready for translation, but this isn't scheduled yet)

Share this post


Link to post
Share on other sites

Thanks for the hard work here Horst! Looks like a very useful and good implementation.

I'm in need of such a tool right now and I can't get it to work. When calling this in a template I get this error.

site/assets/files/1111/source_gartenidylle_031007_151328.jpg
Fatal error: Exception: Method Pageimage::imLoad does not exist or is not callable in this context (in /xxx/dev.urlich/wire/core/Wire.php line 320) #0 /xxx/html/dev.urlich/site/templates/home.php(32): Wire->__call('imLoad', Array) #1 /xxx/html/dev.urlich/site/templates/home.php(32): Pageimage->imLoad('bright_', Object(Pageimage)) #2 

Code is this:

$p = wire("pages")->get(1111);echo $p->image->url;
$img = $p->image;
$pim = $img->imLoad("bright_")->contrast(100)->brightness(100)->pimSave();

The module is loaded and the hook should be added (according to debug admin info) but the error suggests not? I tried with loading the module but then I get another error.

/site/assets/files/1111/source_gartenidylle_031007_151328.jpg
Fatal error: Exception: Cannot load the MemoryImage! (in /xxx/dev.urlich/site/modules/PageImageManipulator/ImageManipulator.class.php line 1216) #0 /xxx/dev.urlich/site/templates/home.php(32): ImageManipulator->contrast(100) #1 

I have no idea what could cause the problem, maybe it's just me and the server.

Some minor things:

- Your modules code has tabs and space indents mixed. Something I'm aware of because I use SublimeText2 and It does what it automatic. :)

- I found the name "PageImage" inconsistent to the core which uses "Pageimage".

- I get a Warning: Invalid argument supplied for foreach() in /xxx/dev.urlich/wire/modules/Process/ProcessModule/ProcessModule.module on line 671 on module screen of PageImageManipulator

1 person likes this

Share this post


Link to post
Share on other sites

 ...

Code is this:
$p = wire("pages")->get(1111);echo $p->image->url;
$img = $p->image;
$pim = $img->imLoad("bright_")->contrast(100)->brightness(100)->pimSave();

it must be $img->pimLoad("bright_")

EDIT:

to the 'minor things' I will have a look later and report back here, promised :)

Edited by horst

Share this post


Link to post
Share on other sites

$img->imLoad("bright_") should be $img->pimLoad("bright") I think.

Don't know why the underscore. and you've a typo in the "pim"

<blink>Horst wins !</blink>

Edited by Martijn Geerts
1 person likes this

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 Robin S
      I have had this module sitting in a 95% complete state for a while now and have finally made the push to get it out there. Thanks to @teppo for his Hanna Code Helper module which I referred to and borrowed from during development.
      http://modules.processwire.com/modules/hanna-code-dialog/
      https://github.com/Toutouwai/HannaCodeDialog
      HannaCodeDialog
      A module for ProcessWire CMS/CMF. Provides a number of enhancements for working with Hanna Code tags in CKEditor. The main enhancement is that Hanna tags in a CKEditor field may be double-clicked to edit their attributes using core ProcessWire inputfields in a modal dialog.
      Requires the Hanna Code module.
      Installation
      Install the HannaCodeDialog module using any of the normal methods.
      For any CKEditor field where you want the "Insert Hanna tag" dropdown menu to appear in the CKEditor toolbar, visit the field settings and add "HannaDropdown" to the "CKEditor Toolbar" settings field.
      Module configuration
      Visit the module configuration screen to set any of the following:
      Exclude prefix: Hanna tags named with this prefix will not appear in the CKEditor toolbar dropdown menu for Hanna tag insertion. Exclude Hanna tags: Hanna tags selected here will not appear in the CKEditor toolbar dropdown menu for Hanna tag insertion. Background colour of tag widgets: you can customise the background colour used for Hanna tags in CKEditor if you like. Dialog width: in pixels Dialog height: in pixels Features
      Insert tag from toolbar dropdown menu
      Place the cursor in the CKEditor window where you want to insert your Hanna tag, then select the tag from the "Insert Hanna tag" dropdown.

      Advanced: if you want to control which tags appear in the dropdown on particular pages or templates you can hook HannaCodeDialog::getDropdownTags. See the forum support thread for examples .
      Edit tag attributes in modal dialog
      Insert a tag using the dropdown or double-click an existing tag in the CKEditor window to edit the tag attributes in a modal dialog.

      Tags are widgets
      Hanna tags that have been inserted in a CKEditor window are "widgets" - they have a background colour for easy identification, are protected from accidental editing, and can be moved within the text by drag-and-drop.

      Options for tag attributes may be defined
      You can define options for a tag attribute so that editors must choose an option rather than type text. This is useful for when only certain strings are valid for an attribute and also has the benefit of avoiding typos.
      Add a new attribute for the Hanna tag, named the same as the existing attribute you want to add options for, followed by "__options". The options themselves are defined as a string, using a pipe character as a delimiter between options. Example for an existing attribute named "vegetables":
      vegetables__options=Spinach|Pumpkin|Celery|Tomato|Brussels Sprout|Potato You can define a default for an attribute as normal. Use a pipe delimiter if defining multiple options as the default, for example:
      vegetables=Tomato|Potato Dynamic options
      Besides defining static options as above, you can use one Hanna tag to dynamically generate options for another. For instance, you could create a Hanna tag that generates options based on images that have been uploaded to the page, or the titles of children of the page.
      Your Hanna tag that generates the options should echo a string of options delimited by pipe characters (i.e. the same format as a static options string).
      You will probably want to name the Hanna tag that generates the options so that it starts with an underscore (or whatever prefix you have configured as the "exclude" prefix in the module config), to avoid it appearing as an insertable tag in the HannaCodeDialog dropdown menu.
      Example for an existing attribute named "image":
      image__options=[[_images_on_page]] And the code for the _images_on_page tag:
      <?php $image_names = array(); $image_fields = $page->fields->find('type=FieldtypeImage')->explode('name'); foreach($image_fields as $image_field) { $image_names = array_unique( array_merge($image_names, $page->$image_field->explode('name') ) ); } echo implode('|', $image_names); Advanced: define or manipulate options in a hook
      You can hook HannaCodeDialog::prepareOptions to define or manipulate options for a Hanna tag attribute. Your Hanna tag must include a someattribute__options attribute in order for the hook to fire. The prepareOptions method receives the following arguments that can be used in your hook:
      options_string Any existing string of options you have set for the attribute attribute_name The name of the attribute the options are for tag_name The name of the Hanna tag page The page being edited If you hook after HannaCodeDialog::prepareOptions then your hook should set $event->return to an array of option values, or an associative array in the form of $value => $label.
      Choice of inputfield for attribute
      You can choose the inputfield that is used for an attribute in the dialog.
      For text attributes the supported inputfields are text (this is the default inputfield for text attributes so it isn't necessary to specify it if you want it) and textarea. Note: any manual line breaks inside a textarea are removed because these will break the CKEditor tag widget.
      Inputfields that support the selection of a single option are select (this is the default inputfield for attributes with options so it isn't necessary to specify it if you want it) and radios.
      Inputfields that support the selection of multiple options are selectmultiple, asmselect and checkboxes.
      You can also specify a checkbox inputfield - this is not for attributes with defined options but will limit an attribute to an integer value of 1 or 0.
      The names of the inputfield types are case-insensitive.
      Example for an existing attribute named "vegetables":
      vegetables__type=asmselect Descriptions and notes for inputfields
      You can add a description or notes to an attribute and these will be displayed in the dialog.
      Example for an existing attribute named "vegetables":
      vegetables__description=Please select vegetables for your soup. vegetables__notes=Pumpkin and celery is a delicious combination. Notes
      When creating or editing a Hanna tag you can view a basic cheatsheet outlining the HannaCodeDialog features relating to attributes below the "Attributes" config inputfield.
      Troubleshooting
      HannaCodeDialog includes and automatically loads the third-party CKEditor plugins Line Utilities and Widget. If you have added these plugins to your CKEditor field already for some purpose and experience problems with HannaCodeDialog try deactivating those plugins from the CKEditor field settings.
    • By joshuag
      Introducing our newest [commercial] module:
      Recurme
      Processwire Recurring Dates Field & Custom Calendar Module.
      http://www.99lime.com/modules/recurme/
      One Field to Recur them ALL…
      A Recurring Dates InputField for your Processwire templates. The InputField you’ve been waiting for.
      Complex RRule date repeating in a simple and fast user interface.
      Use the super simple, & powerful API to output them into your templates.
      example:
      <? // easy to get recurring events $events = $recurme->find(); // events for this day $events = $recurme->day(); // events for this week $events = $recurme->week(); // events for this month $events = $recurme->month(); ?> <? // Loop through your events foreach($events as $event){ echo $event->title; echo $event->start_date; echo $event->rrule; echo $event->original->url; ... } ?> Unlimited Custom Calendars.
      Imagine you could create any calendar you wanted on your website. Use recurring events with the Recurme field, or use your own Processwire pages and date fields to render calendars… it’s up to you. Fully customizable. Make as many calendars as you like. Get events from anywhere. Recurme does all the hard date work for you.
      Unlimited Custom Admin Calendars too.
      Hope you like it  ,
       Joshua & Eduardo from 99Lime.
       




    • By valan
      At our site we use both email and phone authorizations at frontend. To make life easier, I've developed HelperPhone pack that handles phone numbers. This pack includes following modules for ProcessWire CMS/CMF:
      FieldtypePhoneNumber: module that stores phone numbers InputfieldPhoneNumber: module that renders inputfield for phone numbers HelperPhone: module that loads PhoneNumber and PhoneNumberConst classes, and 'libphonenumber' namespace All these modules require included PW WireData-derived class PhoneNumber and PhoneNumberConst.
      PhoneNumber class is a thin wrapper over giggsey/libphonenumber-for-php, itself is port of Google's libphonenumber. PhoneNumberConst class stores constants, used by PhoneNumber class Usage: PhoneNumber class
      $phone = '8 (916) 318-07-29 ext 1234'; // input string could be in any phone-recognizable format $phoneNumber = new PhoneNumber($phone, 'RU'); // or wire('modules')->get('HelperPhone')->makePhoneNumber($phone, 'RU'); echo ($phoneNumber->isValidNumber() ? 'Yes':'No'); // Yes echo ($phoneNumber->isValidNumberForRegion($regionCode) ? 'Yes':'No'); // Yes echo $phoneNumber->getNumberTypeTitle(); // Mobile echo $phoneNumber->getCountryCode(); // 7 echo $phoneNumber->getRegionCode(); // RU echo $phoneNumber->getNationalNumber(); // 9163180729 echo $phoneNumber->getExtension(); // 1234 echo $phoneNumber->formatForCallingFrom('US') // 011 7 916 318-07-28 echo $phoneNumber->formatForCallingFrom('GE') // 00 7 916 318-07-28
      For more methods and properties please refer to PhoneNumber and PhoneNumberConst source files. Need more? Check giggsey/libphonenumber-for-php and use it by accessing $phoneNumber->phoneNumber property - it is instance of \libphonenumber\PhoneNumber or null (if empty).
      Usage: field
      Note: on field creation, make sure that you've configured field settings
      Default region: assumed region if input phone number string is not in international format (starts with '+', etc)
      Enabled/disabled phone extentions: if disabled, phone extension will be removed on field save.
      Phone field settings in example below: default region code 'RU', phone extensions are enabled
      echo $page->phone; // +79163180729 // Note1: $page->phone stores instance of PhoneNumber and renders to string in E164 format. // Note2: E164 format does not include extension. echo $page->getFormatted('phone'); // +7 916 318-07-29 ext. 1234 echo $page->getUnformatted('phone'); // +79163180729 echo $page->phone->format(PhoneNumberConst::RFC3966); // tel:+7-916-318-07-29;ext=1234 echo $page->phone->getNationalNumber(); // 9163180729 Usage: PW selectors
      FieldtypePhoneNumber is instance of FieldtypeText. It stores phone numbers and extensions as string in E164 format with #extention (if provided by user and enabled in settings) E.g. in db it looks like this: '+79163180729#1234'. This makes it easy to query fields as any text field.
      echo $pages->find([     'template' => 'my_temlate',     'phone^=' => '+79163180729', ]); // will echo page ids where phone starts with '+79163180729' Finally
      I've decided to put it here first and later to Modules directory (based on your feedbacks).
      GitHub: https://github.com/valieand/HelperPhone
      Enjoy
    • By justb3a
      Little admin helper module: Using this module you can view all template cache settings at once. E.g. cache status, cache time (configurable). Furthermore it adds the functionality to clear the entire template cache or just the template cache for a given template. Note that this may cause a temporary delay for one or more requests while pages are re-cached.

       
      GitHub: https://github.com/justb3a/processwire-templatecacheoverview
    • By Steven Veerbeek
      Hi,
      I am trying to create a module for a webshop in which I can predefine a number of thumbnail sizes for my product images. I was thinking of storing each of these image sizes as a child page with 'width' and 'height' fields under the module page , so I can use a PageTable input field in my module to easily manage them.
      I know how to create a Pagetable field and add it to templates so I can use it in regular pages, but because I am planning on implementing some other functionalities that (I think) can't be achieved with a regular page, I need the PageTable field to work within a module.
      So far I have come up with this piece of code by trial and error:
      $page = $this->page; $field_sizes = $this->modules->get("InputfieldPageTable"); $field_sizes->title = "image_sizes"; $field_sizes->label = "Image sizes"; $field_sizes->set('parent_id', $page->id); $template = wire("templates")->get("image_size"); $field_sizes->set('template_id', $template->id); $field_sizes->set('columns', "title\nimage_width\nimage_height"); $wrapper->add($field_sizes); It works in that it does display an empty PageTable in my module. I can also add pages and they will be added as child pages under my module page, but when I do, the way the PageTable is displayed gets all messed up. Instead of showing the newly created page as a row in the PageTable, all the fields on the module page (including the PageTable field itself) are repeated within the PageTable field.
      I hope my explanation makes sense. I am fairly new to Processwire (and module development in particular) so perhaps I am just trying to use PageTable in a way it was not intended to be. Maybe you guys could give me some directions on how to achieve what I am looking for?
      Thanks!