Muhammad Usman

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 is 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 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.

Programing Best Practices Violation Fear

Imagine a man named Bob who has a fatal disease and he has a very low chance of living more than a year. Expensive and regular treatment may save him.

Bob needed a new laptop so that he can earn some money from home, he bought one with $400 which comes with 1 year warranty. The sales girl asked him if he needs additional protection plan for $100 which will give him 3 more years of warranty? Bob thought that’s a great deal, it will make his laptop secure for 3 more years and he won’t have to worry about it anymore, but then he thought, even his life is not guaranteed for one year, why would he care about 4 years? It is much better for him to spend $100 on his treatment, it’s the priority now. Bob did not buy the additional protection plan. Smart decision, right?

Now Imagine a Startup

A startup is trying to build a software product on a budget. The developers are very excited, they outlined project idea, wrote user stories, UML diagrams look cool, discussions on high scalability and high availability make them feel smarter than ever, they want rigorous automated testing so they don’t accidentally break anything. Does it ring a bell?

So after a few weeks they started writing unit tests before writing the actual code (because TDD says so).
You know why it’s taking so long? Because they want the project to be maintainable for years to come. Smart decision, right?

Dear sir, it’s a startup building a product, who guaranteed that the startup will exist for years to come, let alone the product? Most of the time, chances are very low that the product will succeed. Just compare this situation with Bob’s situation.

How often do you hear or think a startup or product died because it was buggy, it was poorly coded or it didn’t have unit tests?

What If We Are Building Something That’s Not Gonna Die Soon?

Then you’ll have a budget that’s not gonna die soon. Company will have the resource to decouple you (the developer) from the burden of best practice and architecture.

If you’re just a developer and you think *more* about the architecture than actually writing code and building things, then you’re doing it wrong. It’s a signal that you’re in a team or situation where architecture doesn’t matter too much, if it really mattered then there would have dedicated software architects, you didn’t have to worry too much about it.

Remember, theories of programming are not invented out of air, they exist in our daily life from years. Consider “Single Responsibility Principle”. If a company doesn’t care about it too much in human and you(the employess) have multiple responsibilities like software architecting, development, maintenance, testing then what’s wrong if this company’s codebase has a damn Class named UserAuth having a damn method named userProfile()? Now don’t shout “OMG! OMG! It’s a clear violation of Single Responsibility Principle.”
One masterpiece quote from me to rule’em all:

Break your class’ responsibility according to your responsibility as a team member.

Here comes the disclaimer

I’m not against the best practices, rather I follow many of these practices most of the time. I am against following these blindly, I am against following these out of guilt. These are just rules, and you can break a rule if you need, you can break it when it’s not a priority.

We developers are already much prone to anxiety disorders, writing a line of code and feeling guilty for 10 minutes is nothing less than an Obsessive Compulsive Disorder.

Wish you a guilt-free coding life.

There is a very interesting discussion going on about this post on Reddit,
check it out.

My Lifestyle – Apps and Productivity

Since my childhood, I have always been obsessed with technology. Today I am gonna share with you, how I handle my day to day life using technology. This article just covers some productivity tools that I use. If you find this article helpful then leave a comment down below. If it seems that it’s helping many people then in future I will write about how I handle work, communication, finance, health etc.

I & Setup

I am a software engineer at Vegan Cuts, working remotely from, Sylhet, Bangladesh.

MacBook Pro (Retina, 15-inch, Late 2013), OSX Yosemite
Nexus 5, Android Lollipop

I work from home.

Productivity Tools

Pocket Casts

A great app (not free) for keeping up with and listening to podcasts. When I have time or sometimes when I’m in commute I plug my earphones. Some of the channels I usually follow:
http://www.fiveminutegeekshow.com/
http://www.entrepreneuronfire.com/
http://fullstackradio.com/

Wunderlist

For grocery todos to travel abroad todos, this app is great. It’s a really simple and clean app, but there is also power inside. When I have something in my mind, I just say “Okay Google, make a note to do something” and I can forget about it. I always keep a Wunderlist widget in my home screen.

Rescue Time
It always keeps track of my time, I can see where I spend most of my time when I am in my computer or phone.

Pocket
Most used app in my phone. Have you found a great article and don’t have time to read it right now? Just click the Pocket button. Later you can read it in the comfort of your couch in a nice pleasing-to-eye view. When I like an article so much and I think it’s worth keeping in my library then I share this to Evernote and it saves the whole article for me.

Google Fit
It automatically keeps track of my workouts. Whenever I take a walk or ride my bike with my phone in pocket, this app records it. I don’t have to click play-pause or anything. I can see some stats, like how close I’m with my daily goal.

1Password
Now I don’t have to remember any password. I just press Cmd + \ . The more we can declutter our brain the more we can install creativity. And did I say it’s secure?

Sleep as Android
I have to face captcha if I want to dismiss an alarm.

Blogs and Books

Lifehack.org (not to be confused with lifehacker).
I always follow this blog, they publish some really great articles about productivity and lifestyle in general.

I really admire Sandeep Maheshwari, he is an Indian entrepreneur and motivational speaker. I always watch his videos. Almost all his videos are in Hindi though.

Personally I don’t like much detailed books, so it’s my lacking that I don’t read many books. But some of books I read and I strongly recommend:
Rework
Think and Grow Rich
Remote

I remember while reading Think and Grow Rich, I drew images of some of my dreams as instructed in the book, then I took action. Within 15 months my dreams were fulfilled.

I use the Kobo app for buying and reading books on my phone, I prefer it over Nook because Kobo is available in my country. For reading digital books bought from outside Kobo I use the Kindle app in my phone. I also like paper books but availability and shipping cost matter where I live.

Stay productive!

Charisma – free, responsive, multiple skin admin template

Charisma is a full featured, free, premium quality, responsive, HTML5 admin template (or backend template) based on Bootstrap 3 from Twitter, it comes with 9 different themes to suit your style and application type.

Charisma helps you minimize the repeat work you have to do on you projects. You can re-use Charisma as a base or as a package for your admin panel. It’s free for personal and commercial use and you can use it in multiple sites.

I have put a lot of effort on this, I just expect a share on Twitter or Facebook from you as a “Thank you!”.

Charisma free, premium quality, responsive, multiple skin admin template.

View Live Demo

View on GitHub

Download

If you’re a PHP dev then you may like my projects Pixie Database Query Builder and Strana Pagination Library.

An alternative Download Link (if the Download button doesn’t work).

It is featured with many plugins and UI elements to ease your work. It works on all major browsers and optimizes itself for tablets and mobile phones. Above all it’s 100% FREE and open source. It is licensed under Apache License v2.0, respective licenses apply to all resources used. Issues and pull requests on GitHub are always welcome.

Features

  • 9 different themes
  • Fully responsive, optimized UI for tablets and mobile phones, see how it looks on different devices.
  • Based on Bootstrap 3.
  • Grandmother friendly, works on IE9+.
  • Commented code.
  • Custom product tour, see example.
  • Grid system, see example.
  • Charts, including, pie, stack, flot, realtime etc.
  • Data tables.
  • Widget boxes, collapsible, sortable, closable, see example.
  • Photo gallery, see example
  • Ajaxified menus.
  • Full calendar, monthly weekly, daily, with todo list.
  • Custom error page.
  • Auto active link detection and much more.

UI Elements

  • Custom Tooltip
  • Popover
  • Star Rating
  • Toggle Switch
  • Tag Boxes
  • Multiple File Upload
  • Dialog Box
  • Auto Growing Textarea
  • Ajax Loaders
  • Progress Bars
  • Alerts
  • Pop Notifications
  • Animations

Enjoy 🙂