horst

Page Image Manipulator 1

Recommended Posts

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

  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

  • Like 33

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
  • Like 21

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.

  • Like 1

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!!! ^-^

  • Like 1

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 ;)

  • Like 2

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! :)

  • Like 1

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. 

  • Like 2

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

@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
 

  • Like 2

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!

  • Like 2

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.

  • Like 1

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
  • Like 2

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

  • Like 2

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

  • Like 1

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

  • Like 1

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
  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By BitPoet
      MediaLibrary
      Update: MediaLibrary can now be found in the official module list.
      Out of necessity, I've started to implement a simple media library module.
      The basic mechanism is that it adds a MediaLibrary template with file and image fields. Pages of this type can be added anywhere in the page tree.
      The link and image pickers in CKEditor are extended to allow quick selection of library pages from dropdowns. In the link picker this happens in the MediaLibrary tab, where you can also see a preview of the selected image. In the image picker, simply select a library from the dropdown at the top, everything else is handled by standard functionality.
      I've put the code onto github. This module is compatible with ProcessWire 3.
      Steps to usage:
      Download the module's zip from github (switch to the pw3 branche beforehand if you want to test on PW 3.x) and unpack it into site/modules Click "Modules" -> "Refresh" in the admin Click "Install" for MediaLibrary For testing, create a page with the MediaLibrary template under home (give it an expressive title like 'Global Media') and add some images and files Edit a differnt page with a CKEditor field and add a link and an image to see the MediaLibrary features in action (see the screencap for details) Optionally, go into the module settings for MediaLibrary Note: this module is far from being as elaborate as Kongondo's Media Manager (and doesn't plan to be). If you need a feature-rich solution for integrated media management, give it a look.
      Feel free to change the settings for MediaFiles and MediaImages fields, just keep the type as multiple.
      There are some not-so-pretty hacks for creating and inserting the correct markup, which could probably be changed to use standard input fields, though I'm a bit at a loss right now how to get it to work. I've also still got to take a look at error handling before I can call it fit for production. All feedback and pointers are appreciated (that's also why I post this in the development section).

      Edit 09.03.2016 / version 0.0.4: there's now also a "Media" admin page with a shortcut to quickly add a new library.

      Edit 01.05.2016:
      Version 0.0.8:
      - The module now supports nested media libraries (all descendants of eligible media libraries are also selectable in link/image picker).
      - There's a MediaLibrary::getPageMediaLibraries method you can hook after to modify the array of available libraries.
      - You can switch between (default) select dropdowns or radio boxes in the module configuration of MediaLIbrary to choose libraries.
      Edit 10.10.2018:
      Version 0.1.3:
      - Dropped compatibility for ProcessWire legacy versions by adding namespaces
      - Allow deletion of libraries from the Media overview admin page
      - Added an option to hide media libraries from the page tree (optionally also for superusers)
    • By Robin S
      This module corrects a few things that I find awkward about the "Add New Template" workflow in the PW admin. I opened a wishlist topic a while back because it would good to resolve some of these things in the core, but this module is a stopgap for now.
      Originally I was going to share these as a few standalone hooks, but decided to bundle them together in a configurable module instead.
      Add Template Enhancements
      A module for ProcessWire CMS/CMF. Adds some efficiency enhancements when adding or cloning templates via admin.

      Features
      Derive label from name when new template added: if you like to give each of your templates a label then this feature can save some time. The label can be added automatically when templates are added in admin, in admin/API, or not at all. There are options for underscore/hyphen replacement and capitalisation of the label. Edit template after add: when adding only a single template, the template is automatically opened for editing after it is added. Copy field contexts when cloning: this copies the field contexts (a.k.a. overrides such as column width, label and description) from the source template to the new template when using the "Duplicate/clone this template?" feature on the Advanced tab. Copy field contexts when duplicating fields: this copies the field contexts if you select the "Duplicate fields used by another template" option when adding a new template. Usage
      Install the Add Template Enhancements module.
      Configure the module settings according to what suits you.
       
      https://github.com/Toutouwai/AddTemplateEnhancements
      https://modules.processwire.com/modules/add-template-enhancements/
    • By Mike Rockett
      As I mentioned in this issue, I've create a new textformatter for ParsedownExtraPlugin, which adds some oomph to your markdown.
      Repo: Parsedown Extra Plugin
      Unlike the built-in textformatter for Parsedown and Parsedown Extra, this should be used when you want to use Extra with additional configuration/customisation.
      Some examples:
      ### Test {.heading} - A [external link](https://google.com/){.google} with `google` as a class that opens in a new tab if the config property is set. - [Another link](/page){target=_blank} that opens in a new tab even though it isn't external. ```html .html <p>Test</p> ``` There's some config options available to you, such as setting attributes on all/external images and links, setting table and table-cell alignment classes, adjusting footnote classes and IDs, adding <code> attributes to their parent <pre> elements, and changing the <code> class if your syntax highlighter does not use language-*.
      I was thinking about adding the ability to make links open in a new tab by appending a plus to the link syntax, but only external links should be opening in a new tab anyway. Further, this would add extra, unnecessary processing time.
      Please let me know if you bump into any problems. ☺️
    • By Mike Rockett
      TextformatterTypographer (0.4.0 Beta)
      A ProcessWire wrapper for the awesome PHP Typography class, originally authored by KINGdesk LLC and enhanced by Peter Putzer in wp-Typography. Like Smartypants, it supercharges text fields with enhanced typography and typesetting, such as smart quotations, hyphenation in 59 languages, ellipses, copyright-, trade-, and service-marks, math symbols, and more.
      Learn more on my blog
      It's based on the PHP-Typography library found over at wp-Typography, which is more frequently updated and feature rich that its original by KINGdesk LLC.
      The module itself is fully configurable. I haven't done extensive testing, but there is nothing complex about this, and so I only envisage a typographical bug here and there, if any.
      Please do test it out and let me know what you think.
      Also note that I have indicated support for PW 2.8, but I haven't tested there as yet. This was built on PW 3.0.42/62.
    • By Mike Rockett
      Jumplinks for ProcessWire
      Release: 1.5.50
      Jumplinks is an enhanced version of the original ProcessRedirects by Antti Peisa.
      The Process module manages your permanent and temporary redirects (we'll call these "jumplinks" from now on, unless in reference to redirects from another module), useful for when you're migrating over to ProcessWire from another system/platform. Each jumplink supports wildcards, shortening the time needed to create them.
      Unlike similar modules for other platforms, wildcards in Jumplinks are much easier to work with, as Regular Expressions are not fully exposed. Instead, parameters wrapped in curly braces are used - these are described in the documentation.
      Under Development: 2.0, to be powered by FastRoute
      As of version 1.5.0, Jumplinks requires at least ProcessWire 2.6.1 to run.
      View on GitLab
      Download via the Modules Directory
      Read the docs
      Features
      The most prominent features include:
      Basic jumplinks (from one fixed route to another) Parameter-based wildcards with "Smart" equivalents Mapping Collections (for converting ID-based routes to their named-equivalents without the need to create multiple jumplinks) Destination Selectors (for finding and redirecting to pages containing legacy location information) Timed Activation (activate and/or deactivate jumplinks at specific times) 404-Monitor (for creating jumplinks based on 404 hits) Additionally, the following features may come in handy:
      Stale jumplink management Legacy domain support for slow migrations An importer (from CSV or ProcessRedirects) Feedback & Feature Requests
      I’d love to know what you think of this module. Please provide some feedback on the module as a whole, or even regarding smaller things that make it whole. Also, please feel free to submit feature requests and their use-cases.
      Note: Features requested so far have been added to the to-do list, and will be added to 2.0, and not the current dev/master branches.
      Open Source

      Jumplinks is an open-source project, and is free to use. In fact, Jumplinks will always be open-source, and will always remain free to use. Forever. If you would like to support the development of Jumplinks, please consider making a small donation via PayPal.
      Enjoy!