8 Best Practices for Image Editing in PHP

With this article you will gain a working knowledge of image editing with code. This will be perfect for building systems that automates image editing with a friendly client side interface.

The working example of this is on our latest addition to our websites called “Bespoke Brewery”. What that article covers is how the label designer is put together including some challenges we encountered.



Features of Image Editing in code:

- Adding layers to base image
- Resizing
- Cropping
- Filtering
- Flipping
- Rotating
- Adding text with custom fonts

 

Extras in this Article:

- jQuery Interface
- Working with session variables
- Creating a label designer
- Mobile friendly cropping


1- PHP GD Library

Before you get started in working with php and images you need to remember to install this on the server you will be working with, this library will give you the functionality to use the class system I will talk about later.

The library can be found at http://libgd.org if it is not already installed on the server, those of you with a shared server host will need to check if this is already supplied. If working with a local server (like MAMP, WAMP or XAMP) then you should be able to find “extension=php_gd2.dll” in your php.ini file, just take out the semicolon before it to uncomment it, save the file then restart the local server.


2 - PHP Image Workshop

Sybio is kind of leading the charge in php image class systems. After much research I concluded that his class system would be the best class system solution. His library is completely open source and is available to fork on GITHUB with examples.

https://github.com/Sybio/ImageWorkshop

We found this incredibly easy to work with and the naming conventions for functions are almost in plain english! 

$image = ImageWorkshop::initFromPath(“IMAGE_PATH_HERE”);<br>

$image->addlayer(“Layer ID”,”Another image from init path”,”Position X”, ”Position Y”);<br>

$image->getResult(“ffffff”);<br>

return $image;

For actual code examples please check the tutorials on PHP Image Workshop: http://phpimageworkshop.com/tutorials.html


3 - Using Session Variables

There may be some of you that aren’t keen on session variables but they have a few major advantages, mainly when it comes to remembering (it sometimes works so well to a fault, so include an unset variables button for your own sanity). You can’t change them as easily as you can change cookies.

It works site wide so you can be rest assured that you can use that variable anywhere else in the site without an issue.

For the purposes of the demo session variables have been used to transfer data across pages. This is all controlled by an ajax page being called at every stage transfer which takes certain $_GET[] variables and transfers them into $_SESSION vars. I’ve found this quite effective and user friendly.
 


4 - jQuery/Ajax Interface

New to javascript? http://www.w3schools.com/js/default.asp
New to jQuery? http://www.w3schools.com/jquery/default.asp
New to AJAX? http://www.w3schools.com/ajax/

To make your web application effective with your client you’ll need a jQuery/Ajax interface. This is achieved by working with the Javascript library “jQuery”, if your new or you’ve used jQuery for sometime, something that massively improved our workflow here at Imaginate is the use of JSfiddle. As a team and as an individual it has made us workflow faster and allowed us to keep a record of all our experimental code.

My fiddles: http://jsfiddle.net/user/imagidom/fiddles/


5 - Responsive Scaling for Client Side Image Editing

Cropping online for image editing client side is a tough job already but when your end result is needed to print. So we use a mixture of media queries and JS calcs in order to get the ratio right.

For instance our image is 586px wide and our client screen is on mobile so we decrease the ratio from 60% of our print image down to 30% which would leave our image with a width of 293px…

https://media.giphy.com/media/Eccdry010Mj1m/giphy.gif

This allows for a more elegant client side interface that’s less rigid than the typical standard of image editing.

http://i1188.photobucket.com/albums/z413/Orvana/gifs/cheeringstarterfor10.gif

cheeringstarterfor10.GIF

6 - Mobile Cropping

The way the desktop and the mobile cropping is achieving is by dragging the image in a preview window and a bar to scale with.

In mobile cropping is that there currently is no examples or acceptable standard with it. Our problem with cropping on mobile being that if you tried to drag the image with your finger it would just scroll instead. 

In comes touchpunch.js (http://touchpunch.furf.com/) we were able to achieve the exact cropping UI as our desktop with the help of this library and it’s also a great tool for mobile develop if you interface requires dragging functionality.
 


7) Sentence Structures out of a String

Adding text to an image is not what you would typically associate with editing an image but never-the-less here’s what you need to know…

First off relax you don’t need to go learn another library, it comes as standard in the PHP Image Workshop mentioned earlier and they provide tutorials that make it a joy to use with the exception of one problem.

Structuring sentences from a string this problem was an immediate annoyance as my first thought was surely changing the width and height of the layer would automatically change the text.
(http://www.quickmeme.com/img/48/483ef0911f5e27073a015b45aee7a288b9c8d3bfa104f8bfe6625572f97cfa52.jpg)

 

As it turns out Sybio doesn’t need to structure sentences on text layers but I do so here’s the code.

<code>
// BREAKS UP TEXT INTO SENTENCES
$arrayOutput = array();
$arrayWords = explode(' ', $description);
$maxLineLength = 41;
$currentLength = 0;
$index = 0;

foreach($arrayWords as $word)
{
   $wordLength = strlen($word) + 1;
   if( ( $currentLength + $wordLength ) <= $maxLineLength )
   {
       $arrayOutput[$index] .= $word . ' ';
       $currentLength += $wordLength;
   }
   else
   {
       $index += 1;
       $currentLength = $wordLength;
       $arrayOutput[$index] = $word;
   }
}
foreach($arrayOutput as $sentence){
   $sentenence = 'sentence'.$i;
   ${"$sentenence"} =  ImageWorkshop::initTextLayer($sentence,__DIR__.static::FONT_SAMPLE_PATH, $fontsize, 'ffffff', 0);
   $preview->addLayer(3,${"$sentenence"},78,$top);
   $top = $top+40;
   $i++;
}
</code>

Breaking up the description into words and having a max line length makes it very easy to achieve a sentence structure. Be aware that is the +40 is the lineheight.


8 - Importing it into Wordpress

I was able to get my code into a class library and reference it in shortcodes and pages from within a plugin. Check your jQuery version if you’re using that library because sometimes it might clash. 

Also if you use any SQL statements don’t forget to use wordpress’ $wpdb global and use the activation hook to register the database, this will allow you to install the plugin without having to run SQL in phpMyAdmin.

We integrated the css and the JS in the theme as here we compile everything down to save space and it make development easier for checking code in a team.


Ok.. that’s all folks. Any questions or queries leave them in the comments. 

--

Dominic Cooper-Wootton
Developer, Imaginate

 
wordsmeg egan