Showing posts with label Development spot. Show all posts

Deliver the Perfect Image to Every User with Cloudinary

09:15:00

 

Cloudinary makes delivering perfectly sized and cropped images easy.

What is Cloudinary?

Cloudinary has reinvented the way that media is managed online. It provides a comprehensive cloud-based image and video management solution used by web and mobile application developers at major companies around the world to streamline media management and deliver an optimal end user experience.
Cloudinary Home Page

Main Features

  • On-the-fly image and video manipulation
  • Responsive image delivery
  • Image optimization
  • Digital asset management
  • World-wide CDN network
  • Image/video upload
  • Cloud storage
  • Robust management dashboard
  • SDKs for popular development frameworks

New Features

We'll be taking a look at the new features Cloudinary has announced that make image manipulation and delivery so much simpler.
  • Automatic content-aware cropping
  • Intelligent content-aware encoding
  • Dynamic format selection
  • Automatic responsive images

Automatic Content-aware Cropping

One of the coolest new features includes content aware cropping. Cloudinary automatically detects the region of interest in every image and then crops them on the fly to fit the graphic design and layout, on any device, without losing focus on important content.
It's as easy as setting the gravity transformation parameter to auto.
Take the following url:
Cloudinary Person Face

http://res.cloudinary.com/demo/image/upload/face_left.jpg
Here we're asking to simply return the uploaded image, face_left.jpg.
Now say we want to crop the image, we can set width and height to 200px and request an ordinary crop:
Cloudinary Face Crop

http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_fill/face_left.jpg
Here we set crop equal to fill, which sets gravity to center by default, but as you can see her face is partially cut off. Let's set gravity to auto and see what happens.
Cloudinary Auto Crop

http://res.cloudinary.com/demo/image/upload/w_200,h_200,c_fill,g_auto/face_left.jpg
And just like that, the addition of a single parameter allows us to intelligently crop any image we upload on the fly.
Here's another example

Intelligent Content-aware Encoding

Another problem we face with images is determining the trade-off between image quality and file size. Precise adjustment of compression level complemented by fine tuning of encoding settings can significantly reduce the file size without any noticeable degradation to the human eye. Using Cloudinary's quality transformation parameter, we can automate the file size versus quality trade-off decision based on the specific image content and format.
Cloudinary will deliver  the image with optimal compression and encoding settings, generally resulting in a huge reduction of file size without any noticeable difference in image quality.
Original upload - 569 KB:

http://res.cloudinary.com/demo/image/upload/woman.jpg
Cloudinary Original Image
Automatic quality optimization - 65.9 KB:

http://res.cloudinary.com/demo/image/upload/q_auto:best/woman.jpg
Cloudinary Auto Quality
Comparing the two images, we can see a significant decrease in file size while still maintaining the quality of the image, all done by adding a single parameter to the url.

Dynamic Format Selection

Another way to optimize our images is by utilizing Cloudinary's automatic format selection. This feature allows us to request the best image format based on the user's viewing browser. For instance, we can save bandwidth by delivering WebP images to Chrome users or JPEG-XR to Internet Explorer users, simply by setting fetch_format to auto.
For example, the following jpg image when scaled down to a width of 500 pixels is delivered as WebP to Chrome browsers at 22.4 KB, JPEG-XR to Internet Explorer browsers at 48 KB or delivered as a regular JPEG at 57.5 KB to browsers that don’t support either formats.

http://res.cloudinary.com/demo/image/upload/w_500,f_auto/sample.jpg
Cloudinary Auto Format

Automatic Responsive Images

Last but not least, we'll explore how Cloudinary handles the automatic delivery of responsive images. As developers, we have to make sure we consider the huge range of device screen resolutions that our app may be displayed on. A big problem a lot of us face is deciding what size image to serve depending on the screen size. One resolution just isn't going to cut it anymore.
Our next problem is that it's not always easy to decide just how many versions of the same image should be created.
Should you create 3 different versions of one image? Five? Ten? Cloudinary offers a way to intelligently generate the optimal image sizes for any image on your site. If can easily determine the cost/benefit of every size reduction and only create the number of images necessary. This can all be requested on the fly using just one url.

Read More

Make Composer Auto-Update Itself

02:10:00

 

Composer is a great package manager for PHP. It allows us to install, update and upgrade third-party libraries. For those who don't know about composer, here is a good beginners guide on the topic.
Now we know once in a while, composer needs to update its build so it can have the latest security fixes and patches. This can sometimes get annoying as most people (points to self) forget to update their build. If you have used composer for a period longer than 60days, you might have seen this message.
Warning: This development build of composer is over 60 days old. It is recommended to update it by running "C:\ProgramData\ComposerSetup\bin\composer.phar self-
update" to get the latest version.
This quick tip article aims to tackle that problem by letting composer auto-update itself. For composer to auto-update itself, all we have to is set up a command that runs on a certain interval. I set mine to every Saturday. I assume you know composer and have it installed. For more info, check out this article.

# Setup Composer auto-update on Linux

To make composer auto-update on any Linux-based computer, all we need to do is setup a cron task. Don't know about cron, check out this DigitalOcean article. Open your cronfile and add the command.
5 8 * * Sat /path/to/composer/executable self-update
For example, since my composer executable is in usr/bin, mine cron task will look like this.
5 8 * * Sat /usr/bin/composer self-update
This lets composer update itself every Saturday morning at five minutes past eight.
Note: If you don't know where composer installed on your computer, you can open a terminal and run the following command to get composer's install path.
which composer
Since I use MinGW on windows to make Linux commands available for me, the result of running the above command looks like this.

# Setup Composer auto-update on Windows

As usual, setting up a task like this on windows takes a more graphical approach. On your windows machine, search for task scheduler.
In the right-hand panel on the screen, you should see a list of actions, click on create basic task. In the dialog that pops up, fill in the name and description of the task, click next.

The next section asks you to pick a trigger. Trigger is the event which fires an action. It could be when the computer starts, daily, weekly, monthly etc. Pick weekly and click next.

The next page asks you when to start the task, and the day of the week to trigger the task. For ours, we choose the default start time, input 1 in the "recur every" weeks field, check Saturday as the day of the week and click next.

A list of actions show up, now we can choose to start a program as the action to perform and click next.

On the screen that follows, there is a field for the path to composer.bat and another where we can add arguments. To get the path to composer.bat, in the command prompt type
where composer
and copy and paste the path to composer.bat in the Program/script field. In the Add arguments field, type in self-update or selfupdate either is fine and hit next.

The window that shows up next is the last and final screen, it shows an overview of the task you are creating.

Read More

What is PhantomJS and How is it Used?

02:06:00

 

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.

The above definition may be ambiguous, in simple terms, PhantomJS is a web browser without a graphical user interface.

    In simple terms, PhantomJS is a web browser without a graphical user interface

This then begs the question, What use is a browser without a GUI? A web browser without a graphical user interface is pretty much useless. But because PhantomJS provides a Javascript API, this makes the browser useful. Hence the phrase "WebKit scriptable".
# Installing PhantomJS

Before we learn more about PhantomJS, first you need to install it on your computer. To install PhantomJS, head over to the official website and download the binary suitable for your device.

After downloading the binary, you need to add the executable to PATH environment variable. For Linux users (Mac included), you can place the downloaded binary in usr/bin directory. While Windows users can place the executable in C:\Windows. After doing that, you should be able to open a command prompt or terminal and type phantomjs --help and see a screen like this.

# PhantomJS Core Concepts

Since PhantomJS is not usable when it comes to surfing the web, it has a whole set of features that developers love and use for many purposes.

    Screen capture
    Page automation
    Network monitoring
    Testing
    And more...

Screen Capture

PhantomJS can be used to take screenshots of websites, those screenshots can be rendered in different formats also. Let's spin up a basic javascript script that takes screenshots of a website.

var webpage = require('webpage').create();

webpage.open('https://scotch.io/', function() {
    webpage.render('scotch.png');
    phantom.exit();
});

Running this snippet from a web-browser won't work, we need to load this script using PhantomJS. So we save this snippet in a file screenshot.js, can be anything you want to name it. Then from the command line, run.

phantomjs screenshot.js

Give it a few seconds to run and you should see a file in the same path as screenshot.js named scotch.png, open it and you should see a full page screenshot of scotch.io.
Page Automation

Because we can use PhantomJS to load and manipulate a web page, it is perfect for carrying out page automation. This helps developers run a bunch of tests without ever having to open a web browser.

    Although this may not seem important, this allows us to automate any sort of interactions with a web page without having to open a browser (an operation that will save you a tremendous amount of time).

var webpage = require('webpage').create();

// open scotch.io
webpage.open('https://scotch.io', function(status) {
    if (status !== 'success') {
        console.log('Unable to access network');
    } else {
        var title = webpage.evaluate(function() {
            return document.title;
        });

     // log the title
        console.log(title === 'Scotch | Developers bringing fire to the people.');
    }

    phantom.exit();
});

In the evaluate() method, that's where we write the javascript we want to run on the loaded page. We can save the snippet above in a file and run phantomjs <filename>.js.
Network Monitoring

    Because PhantomJS permits the inspection of network traffic, it is suitable to build various analysis on the network behavior and performance.

We can hook into PhantomJS during a request-response cycle and collect data about the website. This data can be reformatted and allows us to check the performance of a web page.

var page = require('webpage').create();

// hook into initial request
page.onResourceRequested = function(request) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
};

// hook to response
page.onResourceReceived = function(response) {
    console.log('Receive ' + JSON.stringify(response, undefined, 4));
};

page.open(url);

We can use tools like confess.js (a PhantomJS script) and YSlow for a more in-depth network analysis. This is useful in the sense that we can detect regression in the performance of our website before pushing the code.
Testing

This is an important aspect of software development, but developers rarely talk about. PhantomJS has been made popular as a tool for running unit tests. It can run a lot of tests and show the user the result in the command line. Testing tools like Mocha, Casper, just to mention but a few are good examples of testing with PhantomJS as these tools are based on it.
# PhantomJS in the Wild

PhantomJS is used by many companies, you may have used the product and wondered how it was built. For example, Media Queries (source of inspiration for responsive websites) takes a link, checks if the website is responsive, and shows a preview of the website using different screen sizes. The site was made possible thanks to PhantomJS.

A Spanish Life uses PhantomJS to create ads based on user content. Check Out more examples of PhantomJS.

Twitter uses PhantomJS to run QUnit tests on their website.

Read More

A Beginner’s Guide To Composer

11:06:00



Since its release on March 1st, 2012 Composer has gained widespread popularity for bringing something to PHP which was sorely needed: dependency management. Composer is essentially a way to pull in all the third party software such as CSS frameworks, jQuery plugins and others into your project.

I’m sure there are plenty of coders out there who are wondering about the benefits of using composer and many who are afraid to make the leap into a new system. In this article we’ll take a look at what exactly Composer is, what it does and why it is a great tool for PHP projects.

First we’ll take a broader scope look at dependency management and then install composer. We’ll take a general look at usage and then flesh out some of the basics. Let’s get started!
# What Is Dependency Management?

Dependency management is actually a pretty simple concept. Let’s assume you’re creating a one-page website using the Foundation framework for your Javascript and CSS needs. How do you make sure that Foundation is added to your project?

The usual approach is to go to the website, download the package and place it somewhere within your project. So far so good. Now, what do you do when you want to update to the latest version? You repeat the same thing, overwriting the old version.

Let’s assume this goes on for a while and you realize something is broken. They’ve changed something in Foundation and now you have to roll back, but where to? You’ll need to find the older versions and start applying them until you find the right one.

Even if you sort all that out, let’s say you move onto someone else’s project. Are they using Foundation as well? If so, where is it installed and what version is it?

These may not seem like huge issues for a small project but imagine a project with 8-10 dependencies – which still isn’t a lot. Managing everything modularly becomes impossible or – at the very least – a waste of time.

Dependency management solves these problems by automating and standardizing. The retrieval of dependencies such as Foundation, jQuery, Twig, Symphony, logging modules and so on can be done programmatically. Preferred versions can also be designated which protects against conflicts.

A dependency manager standardizes the way the packages are stored and where they are used from. In practice this means that every project that uses the same dependency manager will follow the same structure – at least for dependencies.

# Installing Composer

Composer is available on any system you’d like. On Windows you should use the Composer Setup file which can be found on the Getting Started page. On Linux based systems, including OSX, you can use the following command to install it locally:


curl -sS https://getcomposer.org/installer | php

Run the above command from your project directory. This will give you a composer.phar file which you can use in that directory. I prefer to install the command globally so I can use it in any folder I like. To make this happen, issue the following command as well:


mv composer.phar /usr/local/bin/composer

There are two things which could go wrong. If you need admin privileges here you will need to run this command with sudo.


mv composer.phar /usr/local/bin/composer

In Yosemite this command may fail because the usr directory doesn’t exist. In this case, create the directory structure first and then move the file as usual.

# An Introduction To Composer

There are two separate elements to dependency management with Composer. The first is Composer itself which is a command line tool for grabbing and managing dependencies. The second is Packagist – the main composer repository. This is where the packages you may want to use are stored.

When using Composer the heart of your dependency management will be a single JSON file named composer.json. The nuts and bolts look something like this:


{
    "name": "danielpataki/my_project",
    "description": "My New Project",
    "authors": [
        {
            "name": "Daniel Pataki",
            "email": "mail@mymail.com"
        }
    ],
    "require": {
        "monolog/monolog": "1.12.0"
    }
}

The requirements of you project will be listed in the require section. In this case I’ve required Monolog, a popular framework for logging things. Just because I have a JSON file with this information doesn’t mean I can start using Monolog. Here’s where the command line comes in.

Using the terminal, in the project folder I issue the composer install command. This will bring all my dependencies into the project and do some other neat things.

composer_install

A vendor directory has been created which should contain all dependencies – including composer itself. The screenshot also shows monolog and psr which is a dependency of monolog in addition to a composer.lock file.

At this point you can start using your dependencies but there is a lot more we can learn and do to be more efficient. Let’s go step-by-step and learn a bit more about Composer.

# Specifying Versions

In our code above we wanted to retrieve version 1.12.0 specifically but there may be cases where we want to be a bit more forgiving. There are six ways to specify the version you want, let’s look at them:
Version Range

Using comparison operators you can grab version higher than 1.3, lower than 1.8 or follow an even more complex ruleset by using AND and OR logic. Operators used can be >, <, >=, <= and !=. AND logic is represented by a space or comma, OR logic is represented by double pipes: ||.

Specifying >2.7 would mean any version above 2.7. >2.7 <=3.5 would allow for any version above 2.7 right up until – and including – 3.5.
Wildcard Versions

By using a wildcard you can specify a pattern. 2.3.* would be encompass everything above and including 2.3.0 and below – but not including – 2.4.0. It is equivalent to >=2.3.0 <2.4.
Hyphen Ranges

Hyphen ranges allow you to specify a range more easily, although it is a bit easier to get confused because of how it handles partial versions. A full version consists of three numbers in which case hyphen ranges make perfect sense.

2.0.0 - 3.0.0 is an inclusive range which means that all versions above and including 2.0.0 and below and including 3.0.0 will be accepted.

Partial versions like 2.0 - 3.0 means any version above – and including – 2.0 right up until but not including version 3.1.

The reason for this seemingly weird behaviour is that the left side is inclusive, the right side is completed with a wildcard. The expression above would be equivalent to >=2.1 <3.1.0
Tilde Range

A tilde range is great for targeting a minimum required version and allowing anything up to, but not including, the next major release. If you specify ~3.6 you are allowing 3.6 and everything up to, but not including 4.0.

This method of specifying a version is equivalent to >-3.6 <4.0.
Caret Range

The caret range is meant to allow all non-breaking updates. If a project follows semantic versioning there shouldn’t be any enhancements that break compatibility within a major branch. That is to say any thing above and including a major version and below and not including the next major version should be safe to use. By specifying ^3.3.5 you are allowing anything right up to, but not including, 4.0.
Dev-Master

By specifying dev-master you are grabbing the currently developed latest release which hasn’t been tagged with a version number yet. This can be just fine while developing but you need to be aware that the potential for bugs is higher in these versions.

# Locking

Locking of dependencies is one of the most useful features of Composer. I mentioned the composer.lock file eariler. What this does is lock down the versions of the used components.

The lock file can make sure that everyone works with the same versions of files. Just because the application shouldn’t break due to a component update doesn’t mean that all your teammates and your production server should all be running separate versions.

When you first use Composer to grab a dependency it writes the exact version to the lock file. If you specified 2.3.* and 2.3.5 is the latest version the installed version will be 2.3.5 and it will be entered into the lock file.

Let’s say a developer joins the team 10 days later. By this time the dependency has been updated to 2.3.6. If he uses the correct command (composer install) he will receive 2.3.5 because it is locked in place.

You can of course decide to update your dependencies. In this case you should run composer update. This will grab the latest versions allowed and write them to the lock file. This will then be distributed to all sources which can in turn be updated.

# Development Requirements

Composer allows you to specify development requirements. This is done by specifying your requirements in the require-dev array instead of the require array.


{
    "name": "danielpataki/my_project",
    "description": "My New Project",
    "authors": [
        {
            "name": "Daniel Pataki",
            "email": "mail@mymail.com"
        }
    ],
    "require": {
        "monolog/monolog": "1.12.0"
    },
    "require-dev" : {
        "fzaninotto/faker", "dev-master"
    }
}

Faker is a PHP class that generates fake data. This is great for development but in production it reallt isn’t required.

Be aware that development requirements are always installed by default, Composer doesn’t magically know when it is being run on your production server. If you want to exclude development requirements you will need to run the install or update command with the --no-dev option.

# Composer In The Wild

Composer is used everywhere in the PHP World. All large and well-known website components such as jQuery, Foundation, Bootstrap, even WordPress itself has a composer package available.

In addition, smaller but equally useful code can be retrieved via composer. Logging packages such as monolog, PHP mailers, string manipulation classes, PHP Unit and other tools also around.

The framework community has benefited greatly from Composer’s capability to unify project requirements. The much-adored Laravel, FuelPHP, Yii Framework and others rely on composer for bringing together shared functionality for projects.

The biggest benefit is of course hidden from view. Composer is great when you need to share or deploy code. You don’t need to lug around 20-50Mb of related but unused code. You can just check in the composer.json and lock files and everyone will be on the same page within minutes.

# Conclusion

There are many-many more things you can do with Composer but I hope I’ve given you a glimpse into its power. In addition to what we talked about, Composer gives you excellent autoloading out of the box, you can hook scripts into any step of the update processes and so on.

Any group project should use Composer but it’s pretty useful even if you work alone. It gives you a lot of flexibility and it future-proofs your project – you never know when you may need an extra hand with it!

Read More