Linux command line Image Manipulation for Android Developers

Sometimes while developing Applications for Android one has to transform a lot of images at once. In those cases, it is easier to use the command line than standard programs such as gimp.

Resize multiple Images via Command Line

for i in *.png; do convert "$i" -resize 50% "${i%%.png*}.png"; done

I use this a lot when developing for Android, as it is best to supply differently sized images for different devices to save memory.

Lets say I want to display a couple of square icons. The width of the icons should be 1/4th of the screen. I would create base icons with a dimension of 500×500 pixels. The images should be 60×60/80×80/120×120/160×160 pixel for ldpi/mdpi/hdpi/xhdpi respectively. What I do is copy the base images to the correct subdirectory of the res folder and execute the following commands in it (the percentage is calculated by dividing the desired width through the base width, for example: 80/500 = 0.16 = 16%):

# from base
# to xhdpi:
for i in *.png; do convert "$i" -resize 32% "${i%%.png*}.png"; done
# to hdpi:
for i in *.png; do convert "$i" -resize 24% "${i%%.png*}.png"; done
# to mdpi:
for i in *.png; do convert "$i" -resize 16% "${i%%.png*}.png"; done
# to ldpi:
for i in *.png; do convert "$i" -resize 12% "${i%%.png*}.png"; done

Optimize multiple Images via Command Line

I use optipng as well as advpng to optimize the size of my images:

optipng *.png -o5
advpng -z --shrink-insane *.png

Missing PHP String Functions: contains, equals and more

PHP is great because it is easy to deploy it on pretty much any webserver. But in my opinion the language itself is not very well designed. In this post I will take a look at the PHP string functions and offer implementations of those important string functions that PHP is missing.

PHP and Java String functions compared: A Rant

If you look at the Java String class it has all methods that one commonly needs for strings, and the method signatures are well designed. Even without remembering the exact names, it is easy to guess the method names as well as the arguments.

Now take a look at the PHP String functions. Some function names start with “str” (e.g. strpos), some end with “str” (e.g. substr), and some do not contain “str” at all (e.g. strip_tags). Some use an underscore to seperate (e.g. str_replace) and some do not (e.g. strnatcmp). And many are abbreviated in a way that results in an awful method name. I can maybe guess what strrev is supposed to do, but what about stristr, strpbrk or strchr (which is only an alias for strstr). We measure hard disks in gigabyte and terabyte, it is ok to waste an extra bit or two for a decent function name.

So I think that it is fair to say that the naming convention for PHP String functions is non-existent and that one either has to remember every method name or search for it each time it is used.

As if that wasn’t enough, some of the most important functions such as equal and contains do not even exist in PHP.

Important Java string functions to PHP

The string functions contains, equals, endsWith, startsWith, and – to a lesser extend – charAt are vital when working with strings, but they are missing from PHP. So here they are:

// does $big_string contain $small_string ?
// the empty string is contained by all strings.
function contains($big_string, $small_string) {
    if (strlen($small_string) == 0) {return true;}
    return (strpos($big_string, $small_string) !== false);

// are the given strings equal (case-sensitive)?
function equals($string1, $string2) {
    return !strcmp($string1, $string2);

// does $big_string start with $small_string?
// every string starts with the empty string
function startsWith($big_string, $small_string) {
    return !strncmp($big_string, $small_string, strlen($small_string));

// does $big_string end with $small_string?
// every string ends with the empty string
function endsWith($big_string, $small_string) {
    if (strlen($small_string) == 0) {return true;}
    return (substr($big_string, -strlen($small_string)) === $small_string);

// returns character at the given $position of $php_string
// or empty string if $position is outside of the string.
function charAt($php_string, $position) {
    if ($position < 0 || strlen($php_string) <= $position) {return '';}
    return $php_string[$position];

And just for reference, here are five often used PHP string functions and their Java equivalent. I’m thinking of collecting some more and wrapping them up in coherently named function names, but I could also try to remember 5 function names :)

build-in php string functions (equivalent Java methods added in "[]"):

int strlen ( string $string ) [length] - returns length of string

string strtoupper(string $string) [toUpperCase] - returns given string to all upper-case

mixed str_replace(mixed $search_string, mixed $replace, mixed $subject) [replace] -
replaces given $search_string in $subject with $replace.

int strrpos ($big_string, $small_string) [lastIndexOf] -
returns the position of the LAST(!) occurrence of $small_string in $big_string

string substr ( string $string , int $start [, int $length ] ) [substring] -
returns a substring of the given string. first character is position 0, as it is in Java. BUT PHP expects the length of the substring as second parameter, while Java expects an index instead.

If there are any important PHP string functions that I missed, please feel free to add them in the comments!

Linux #4: Difference between find, locate and whereis

Difference between find, locate and whereis linux commands

find: finds files by filename. see Linux: Search for a File by Filename for more details and example usages.

locate: also finds files by filename but does not search the directory structure itself but only a database prepared by updatedb. Because of that locate is faster than find but less accurate. Examples:

locate firefox
# ->    /etc/firefox
#       /etc/firefox-3.0
#       /etc/firefox-3.5
#       /etc/alternatives/firefox-homepage
#       /etc/alternatives/firefox-homepage-locales
#       [ ... and many more results ... ]

locate a_file_that_i_just_created
# -> no results

whereis: finds source, binary and manual files by name. Examples:

whereis find
# -> find: /usr/bin/find /usr/share/man/man1/find.1.gz

whereis firefox
# -> firefox: /usr/bin/firefox /etc/firefox /usr/lib/firefox /usr/lib64/firefox /usr/share/firefox /usr/share/man/man1/firefox.1.gz

Which to use: find, locate or whereis

It really depends on what you want to do:
If you want to find a linux program (or its source or documentation) use whereis.
If you want to find an often-used file or want to perform a quick but not too accurate first search for a file use locate.
If you want to find one of your personally created files use find if you know approximately where to look or have a lot of time (searching for a file by name using find from the root takes some time). If you do not, use locate first as it is quicker. If it did not find the file you can still use find afterwards.

Symfony2 Flash Message

Flash Messages make it possible to show a string on the next request, for example after a redirect.
This is useful when you want to inform a user about the success or failure of form-requests.

Symfony2 changed how flash messages work from version 2.0 to 2.1, so below you can read about how to use flash messages in both versions.

Symfony2 flash message for Symfony 2.0 and below

Setting the flash message

To add a flash message – which lasts exactly one request – to a session use this code in the controller:

$this->get('session')->setFlash('notice', 'Form successfully executed!');
First we retrieve the Session Object and then set a flash message. notice is the name which you can set to anything you want and Form successfully executed! is the content of the message.

Retrieving and displaying the flash message

To display a message in the view, use the following twig code:

{% if app.session.hasFlash('notice') %}
    <div class="flash-notice">
        {{ app.session.flash('notice') }}
{% endif %}
First we check if there is a flash message and if it exists we display it.

Flash messages for Symfony 2.1 and above

Setting the flash messages

In version 2.1 of Symfony2 not too much changed about flash messages. They are now stored in a so called flashbag which allows to store more than one message under a name:

$this->get('session')->getFlashBag()->add('notice', 'Form successfully executed!');
$this->get('session')->getFlashBag()->add('notice', 'Yes, really!');

Retrieving and displaying the flash messages by name

you can now display all flash messages that you added under the name notice:

{% for flashMessage in app.session.flashbag.get('notice') %}
    <div class="flash-notice">
        {{ flashMessage }}
{% endfor %}

Retrieving and displaying all flash messages

It is also possible to iterate over all flash messages (stored under all names) and display them:

{% for type, flashMessages in app.session.flashbag.all() %}
    {% for flashMessage in flashMessages %}
        <div class="flash-{{ type }}">
            {{ flashMessage }}
    {% endfor %}
{% endfor %}