Image Manipulation in Golang – Convert Image to Grayscale

One of the things I love about Go is it’s powerful collection of standard libraries, one of those is the image library. I’ll show you how you can have a fun exercise or a weekend project in Go, that’ll convert an image to grayscale (or kinda black and white). This tutorial will help you learn standard image library or if you’re new to Go it’ll teach you some basic concepts of Go.

First thing first, create a file greyjoy.go, I mean, why not Greyjoy? We’re having joy/fun with grey. Paste the following code in the file.

package main

import (
    "os"; "image"; "image/jpeg"; "image/color"
    "path/filepath"; "fmt"; "log"; "strings"
)

func check(err error) {
    if err != nil {
        panic(err)
    }
}

func main() {
    // ... All your code will go here
}

Our code will compile to a binary file, and we will call it like greyjoy firas.jpg and it’ll save the grayscale version as firas_gray.jpg.

So let’s get the first argument passed to our binary and if it’s not given then exit with a message. Again all of these code will go under the main func above.

if len(os.Args) < 2 { log.Fatalln("Image path is required") }
imgPath := os.Args[1]

Let’s open the given file, check any error and instruct Go to close the file when we’re done.

f, err := os.Open(imgPath)
check(err)
defer f.Close()

Now decode the image using the image library and report if the image is not JPEG. PNG and GIF can be easily supported but we’re not going that far.

img, format, err := image.Decode(f)
check(err)
if format != "jpeg" { log.Fatalln("Only jpeg images are supported") }

Cool, we’ve the image decoded in the img variable and its pixel are ready to be read, however it’s readonly, means we can’t manipulate this img.
So, let’s create a blank image where we can write:

We will get the size of the given image and we will create a blank RGBA image with the same size (X and Y coordinates).

size := img.Bounds().Size()
rect := image.Rect(0, 0, size.X, size.Y)
wImg := image.NewRGBA(rect)

Now we will loop through all the pixels in img, get the pixel, make it gray by applying a simple grayscale algorithm and write that pixel to wImg.

// loop though all the x
for x := 0; x < size.X; x++ {
	// and now loop thorough all of this x's y
	for y := 0; y < size.Y; y++ {
		pixel := img.At(x, y)
		originalColor := color.RGBAModel.Convert(pixel).(color.RGBA)
		
		// Offset colors a little, adjust it to your taste
		r := float64(originalColor.R) * 0.92126
		g := float64(originalColor.G) * 0.97152
		b := float64(originalColor.B) * 0.90722
		// average
		grey := uint8((r + g + b) / 3)

		c := color.RGBA{
			R: grey, G: grey, B: grey, A: originalColor.A,
		}

		wImg.Set(x, y, c)
	}
}

Let’s simply encode wImg and save it to disk with the same name that was given but we will suffix it by _gray.

ext := filepath.Ext(imgPath)
name := strings.TrimSuffix(filepath.Base(imgPath), ext)
newImagePath := fmt.Sprintf("%s/%s_gray%s", filepath.Dir(imgPath), name, ext)
fg, err := os.Create(newImagePath)
defer fg.Close()
check(err)
err = jpeg.Encode(fg, wImg, nil)
check(err)

Now we will build our binary by running this in the command line:

go build

and it’ll create a binary called greyjoy. Now let’s run this binary and provide the input image path, it’ll output the gray image in the same path.

./greyjoy firas.jpg 

Hope you enjoyed the tutorial!

Ajaxify Your Laravel Application Automatically

You have a “nice little” Laravel app. You return views from your controllers, you redirect with a flash message when you’re done with something or when something goes wrong.

But sometimes you need to send Ajax requests to the server. And this time those views and redirects don’t make sense. You need JSON response. You create two different methods in your controller, one returns JSON and one returns View, because you also want the page to be loaded from server when user(or search engines) hit the url directly. And now things start to get messy.

What if you can write an HTTP Middleware which detects Ajax requests and converts responses to Ajax compatible responses? For example turn the response of this:

$user = ['name' => 'Usman', 'email' => '[email protected]'];
return View::make('user.show', $user);

into this
{"name": "Usman", "email": "[email protected]"}

or response of this

return Redirect::to('/')->with('error', 'User not found');

to this

{"error": "User not found"}
// with a 301 header

That’d be great, right? All this can be automated, I will show you how.

Let’s Code

We’ll create an HTTP middleware by running php artisan make:middleware Ajaxify
Or just create the class manually in (app/Http/Middleware/).

It’ll look like this:

<?php

namespace App\Http\Middleware;

use Closure;

class Ajaxify
{
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

Handle Method

Here we basically use couple of helper methods, which we’ll create next.
We check if we really need to alter the original response or not. Then we check if the response is successful (it has 20* status code) or not. If yes, we get all the the data passed to our view and then return the data as JSON response. It’s the key thing here.

If the response is not successful, we get all the flash data. If we have them then we return the flash data as a JSON response.

public function handle($request, Closure $next, $guard = null)
{
    // Get the original response
    $response = $next($request);

    if (! $this->shouldAjaxify($request, $response)) {
        return $response;
    }

    // A 20* response
    if ($response->isSuccessful()) {
        $originalContent = $response->getOriginalContent();
        // Get the data we passed to our view
        $data = $originalContent->getData();
        // Return the data passed to view as JSON response
        return response()->json($data);
    }

    // We don't have a successful response,
    //  we rather have a redirect like response

    $flashData = $this->getFlashData($request);
    if (! count($flashData)) {
        return $response;
    }
    // Return all the flash data as JSON
    return response()->json($flashData, $response->getStatusCode());
}

Helper Methods

Now we’ll add couple of protected methods in the class. First one is to help us determine if we should convert the response to JSON response or not.

protected function shouldAjaxify($request, $response)
{
    // If we already have a JSON response we don't need to do anything
    if ($response instanceof JsonResponse) {
        return false;
    }

    // If there is a server (status 50*) error, we won't do anything
    if ($response->isServerError()) {
        return false;
    }

    // It's not a View response
    if ($response->isSuccessful() && ! method_exists($response->getOriginalContent(), 'getData')) {
        return false;
    }

    // Now if it's an Ajax request or the clients wants a JSON response or we've
    //  a query string param 'ajaxify' then we'll Ajaxify, else we won't.
    return $request->ajax() || $request->wantsJson() || $request->exists('ajaxify');
}

So this method basically determines if we need to alter the response or just ignore it.

Now another helper method to get all flash data from the session:

protected function getFlashData($request)
{
    // Get all session data and convert the array to a Collection object
    $sessionData = collect($request->session()->all());
    // Filter only flash data from session data
    $flashedKeys = $request->session()->get('flash.new');
    $flashData = $sessionData->only($flashedKeys);
  
    // Delete flash data, as we've already used them
    $request->session()->forget($flashedKeys);
    return $flashData;
}

Finally

Register our middleware as a global middleware, by going to this file app/Http/Kernel.php.
in the web section we will add this:

protected $middlewareGroups = [
        'web' => [
            ...
            \App\Http\Middleware\Ajaxify::class,
        ],
        ...
    ];

Now you can try sending an Ajax request to your existing route or just try this in your browser: http://yourapp.dev?ajaxify

Caution:
Do not pass sensitive data to your view or to flash session. It will expose all data. Be careful when passing full model, use $hidden and $visible properties in your models to secure sensitive database fields.

Don’t Fear Exceptions

If you’re not one of the few, you surely get scared once you see one of these:

Fatal error: Uncaught exception ‘Exception’ with message ‘Not found’ in /home/usman/www/test.php on line 27

Fatal error: Uncaught exception ‘UnexpectedValueException’ in /home/usman/www/test.php on line 27

When you see Red or Orange screen with Exception you fear like you’ve committed a sin and just go back to code to repent. Congrats, you’re the majority.

What if I told you that Exceptions are no sin, rather blessings of object oriented programming?
What if I told you that an Exception doesn’t just mean that your code is wrong?

Let me show you how.

For example code, I am using Laravel PHP framework. But the knowledge is not Laravel specific. This article assumes that you know basics of Exception and how to catch it.

An Example

I believe in practical example, so rather than preaching, I am showing you a real life example.

It is really common, when a you search for an entry in database, you check if this entry exists. If not then you show an error.

$person = Person::find($id);

if (! $person) {
    // Show message: Person not found
}

// Person found
return View::make('person.show', compact('person'));

You handle this problem with an if everywhere, why? Why don’t you just throw an exception when something doesn’t exist? Do just this:

$person = Person::findOrFail($id); // Will throw an exception if not found
return View::make('person.show', compact('person'));

In just one place catch this error. For Laravel, put this in your app/start/global.php:

App::error(function(\Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
    return 'Entry not found'; // You can show 404, or do whatever you want
});

If you’re not using Laravel then catch the exception using try-catch when you boot your application.

Advantages of Using Exceptions

An Exception is just what is not expected. Be fearless to throw an Exception whenever you think something is not expected and the function/method/application should stop executing further.

One of the big advantages of using Exception over traditional redirect, die/exit is that you separate your business logic from your transport layer(ex, HTTP).

For example, you use a direct HTTP redirect when a form validation fails. Now what if the end user is not using a browser at all, he is using your mobile app which uses the same business logic with an API? What if you’re unit testing? What if you’re firing a background job with CLI? No HTTP at all, now how?

You’re right, Exception. Create a class ValidationException which extends \Exception. And whenever a validation fails:

    throw new ValidationException('Hey kid, you forgot your name?');

Now catch this Exception:
In case of usual HTTP use, do a redirect.
In case of API, set a status code with JSON message perhaps.
In case of CLI, just dump the error message.

In the Example section above, you’ve seen another advantage. How we made our code simple and DRY(Don’t Repeat Yourself).
There are many other advantages, I’m not going over everything, please check this article if you’re not convinced.

In the end

I ask you one thing, please do yourself a favor, make use of object oriented best practices(like utilizing Exception) where it fits, you won’t regret. Our PHP community has been late in this regard, but the revolution is coming.

Please feel free to share your thoughts.

If you’re a Laravel developer then you may also like my model self-validating package with Exception – DRYVal.

PHP Router in 140 Characters

This is a dimple(damn simple) URL routing script for PHP which is written in just 140 characters of code, so it fits within a tweet.

Its NOT a good router at all, don’t use it in a real application, its not exception handled either. I did it just for fun and to demonstrate the simplicity

So here’s the router code, and that’s all (seriously).

class R{
function a($r,callable $c){$this->r[$r]=$c;}
function e(){$s=$_SERVER;$i='PATH_INFO';$p=isset($s[$i])?$s[$i]:'/';$this->r[$p]();}
}

Fork on GitHub.

Usage

Create a file index.php in your server root and try this code

<?php
// The router code
class R{
function a($r,callable $c){$this->r[$r]=$c;}
function e(){$s=$_SERVER;$i='PATH_INFO';$p=isset($s[$i])?$s[$i]:'/';$this->r[$p]();}
}
//


// Create 
$router = new R();

// Add a route with a callback function
$router->a('/a', 'callbackFunction');

// Add a route with a closure
$router->a('/b', function(){
    echo 'Hello B';
});

// Add homepage route
$router->a('/', function(){
	echo 'Hello World';
});

// Add route with class method
$router->a('/c', [new Foo, 'bar']);
// Add multiple slashed route with class method
$router->a('/c/d', [new Foo, 'bar']);

// Execute the route
$router->e();

// Callback handlers
function callbackFunction(){
	echo 'Hello A';
}

class Foo{
	function bar(){
		echo 'Hello Bar';
	}
}

Now visit your server root http://localhost/index.php, http://localhost/index.php/a, http://localhost/index.php/b, http://localhost/index.php/c and http://localhost/index.php/c/d.

Or you may run built-in PHP server from the command line (in the same dir)

[code]
php -S localhost:8081
[/code]

and visit http://localhost:8081/index.php.

Runs on 5.4+. 140 chars idea is inspired by Fabien Potencier’s Twittee.

Laravel 4 Uses Lots of Static, Not True.

Most of the time developers blame Laravel for using too much static. This claim is not true in case of Laravel 4, lets dig in and discuss why and how.

What is static?

In PHP you call it like this Class::$property.

As the name suggests, it preserves the state. Static variables preserve their values across the lifetime of the running application(in our case request). In a class if a static property is declared it becomes the property of the CLASS itself, NOT the property of the instance(s) of the class.

Why is static considered bad?

Well, there are debates. One of main reasons is, you can’t (quite) Mock a static variable or method as its difficult to override statics because the state is preserved and no object/instance is used. This makes it really difficult to Test(Unit Test) an application as Mocking is a must needed thing to unit-test an application fully.

When you start unit-testing your application then you will realize why static dependencies are so bad. It becomes quite impossible to replace implementations during testing. So you end up creating lots of hacks just for maintaining testability.

How does Laravel static work?

Laravel 4 doesn’t actually use static rather it mimics the static calling behavior. When you call a static method, actually much more things happen behind the scene than it appears. Lets go through the life cycle of a static call.

As an example we’re calling View::make('hello').
You will see literally there is no class View under the \ namespace. Rather Laravel uses aliases, so when you look at app/config/app.php, you will see View is just an alias of Illuminate\Support\Facades\View. So you’re actually calling:

Illuminate\Support\Facades\View::make('hello');

When we go to Illuminate\Support\Facades\View under (vendor/laravel/framework/src) we see just this code:

class View extends Facade {

	/**
	 * Get the registered name of the component.
	 *
	 * @return string
	 */
	protected static function getFacadeAccessor() { return 'view'; }

}

It extends the base Facade class, and in both classes there is no static method make(). The magic happens on the base Facade class, where there is a magic method __callStatic. This is called PHP Overloading, whenever you call a static method and this class doesn’t have that method then __callStatic is called(like a 404 page) with the called method name(‘make’) as the first parameter and the called parameters’ array as second parameter(array(‘hello’)).

What __callStatic does basically here, it calls the IoC Container binding with the name ‘view’ and calls the (non-static)method (‘make’) within it. What IoC Container contains, a pure instance of the original View class, in an object oriented way (not a class oriented way). So we can re-write the View::make('hello') as

$app->make('view')->make('hello')

Conclusion

Now we know Laravel makes it super easy to call methods which makes it look like static but actually its not, so we can easily mock the original View class and get our tests pass. Using these facades for static call is just a way to access Laravel classes, you can write your entire app without using these facades(static calls). Do you find anything incorrect, do you have something better to share? Please write in the comments.