Jonathan Miles, Freelance Web Designer

Basic image optimisation mistakes (crimes against images)

January 10th, 2010

Image optimisation is about making images that are suitable for the web. That means reaching a balance between file size and quality, to ensure an image looks good and downloads fast.

There are a few mistakes that beginners often make.

Mistake 1: Unnecessarily big images

A classic mistake is to use a big, high resolution image without shrinking it properly. A big image has lots of pixels and each one adds to its file size, making it download slower.

The incorrect way to shrink an image is to write HTML code like this:

1
<img src="my-really-big-image.jpg" width="200" height="150" />

The code above tells the web browser to display “my-really-big-image.jpg” at a size of 200 x 150 pixels. If the image is 3000 x 2000 pixels then all that’s doing is displaying it at a smaller size. The image itself is still 3000 x 2000 pixels and that means it’s still going to download slowly.

Below is a simulation of what happens when a big image is displayed at a small size on a web page:

An unresized image downloads slowly

The image downloads slowly because there’s lots of pixels. It takes so long that you can see it loading. It also looks awful because there are jagged edges. Web browsers are bad at resizing images.

The correct way to shrink a big image is to use a graphics program to resize it. You end up with something like this:

A properly resized image

Notice how the quality is much better. The street light on the right is far less jagged and you can make out more detail. It also loads way faster. The original photo had a file size of 1.7mb but the small version is just 9kb. Or to it put another way, it’s 188 times smaller.

Real examples of images that are too big

Using bigger images than needed is a common mistake. It’s easy to find examples with the help of Google:

Google image search: “the team”

The above google search looks for large images on pages containing the phrase “the team”. This tends to find pages where organisations are introducing their staff members and haven’t resized the team photo properly.

Mistake 2: Wrong image format

Image data can be stored in different formats. There are lots of formats and each has its own strengths and weaknesses, so choosing the right one is important.

Most people are probably familiar with the JPG format because it’s great for photos. That doesn’t mean it’s good for everything though. JPG is bad for images that have lots of solid colour and crisp lines. It’s much better to use the PNG format for those kind of images. Take a look at this zoomed in comparison:

The PNG on the left is perfect. The JPG on the right has compression artifacts.

The PNG on the left is perfect. The JPG on the right has compression artifacts.

JPG is a lossy image format. That means it compresses the image data by discarding parts the human eye won’t notice. It works well for photos but the clean, crisp lines of an illustration can suffer from noticeable compression artifacts.

PNG on the other hand is lossless, so it can preserve images perfectly. It works best for images with clean, crisp lines such as vector art work, logos, certain comics and so on.

This comic showing PNG vs JPEG makes the point well (with a tiny bit of exaggeration).

Mistake 3: Squashing people (aspect ratio abuse)

I recently came across a website where the client had created a banner graphic from a photo but completely ignored the aspect ratio, so it looked like this:

It looks squashed because the aspect ratio is wrong

It looks squashed because the aspect ratio is wrong

The image above is 400 pixels wide and 50 pixels tall but you can see that it’s been squashed vertically, making the people look short and fat. That’s what happens when you get the aspect ratio wrong.

The aspect ratio is found by dividing the image’s width by its height, so in this case we do 400 / 50 = 8. That gives an aspect ratio of 8:1, meaning that for every 8 pixels of width there’s 1 pixel of height. To create an image that isn’t squashed, the original photo will have to be cropped to the correct aspect ratio.

Photoshop has a Rectangular Marquee tool that can be set to a fixed aspect ratio:

Using Photoshop's fixed ratio selection

Once you’ve set the desired ratio you can draw a selection and it’ll always be the right aspect ratio. It’s then just a case of cropping to your selection and saving.

The people aren't squashed now the aspect ratio's correct

The people aren't squashed now the aspect ratio's correct

That looks better. Notice how you don’t see as much of their bodies as before – that’s because those parts had to be cropped out. The first image looked squashed because it was cramming an image that was too tall into the same space.

The end

If you’re not making any of the basic mistakes that have been discussed here then you’re probably doing okay.

Debugger statements make YUI Compressor error

November 18th, 2009

YUI Compressor 2.4.2 gave me this error when I tried to minify a JavaScript file:

1
[java] [ERROR] 4447:21:identifier is a reserved word

Line number 4447 is a code block like this:

1
2
if (debugging)
    debugger;

The problem is the debugger statement – I’m not sure why because it isn’t being used as the name for a variable like the error seems to imply (reserved words, like debugger, have special meanings and so can never be used as identifiers).

Removing the debugger statement would avoid this error but the statement’s there for a reason, so that’s not an option in this case.

The trick is to hide debugger from YUI Compressor:

1
2
if (debugging)
    eval("debugger");

Now all YUI Compressor sees is an innocent eval statement.

The Beatles: Rock Band

September 18th, 2009

The Beatles: Rock Band

My copy of The Beatles: Rock Band for the Wii arrived last Friday – not on the Wednesday, despite GameConnection‘s claim that pre-orders are dispatched to “arrive on the day of release” (I have an email telling me it was dispatched on the game’s release date). I’m a patient person though, so a short wait wasn’t a big deal – and given the recent postal disruption I’m probably lucky it turned up as quickly as it did.

The game itself plays like the other instalments in the Rock Band series, so there aren’t many surprises – it’s simply a fusion of The Beatles and Rock Band. It’s very well done though, with a slick opening cinematic that leads you into a game that has great presentation throughout. The visual sequences that accompany each song are particularly noteworthy, though when you’re playing you don’t have time to properly admire the effort that’s gone into them.

This is the third music rhythm game I’ve played, so while I’ve been enjoying it there isn’t the same novelty value as before. I’m also getting fairly good due to all the practise I’ve had, so a relatively small game like The Beatles: Rock Band, which has 45 songs, only takes a few days to work through.

Unlockable rewards are a welcome addition to the game, giving an incentive to go back and five star all the songs so that you can get all the photos, background information and video clips.

The game’s story mode is split into chapters that follow The Beatles’ career. After completing a chapter you can go back and try the chapter challenge, in which you play the songs from that chapter back to back (with the aim of five starring them all). This works really well for the first few chapters of the game, which tell the story of The Beatles’ touring career, because the minimal down time between songs really adds to the feeling of playing a live set. It’s not quite so good for the Abbey Studio era because you lose the feeling of playing to an audience (well, an imaginary audience) and the intricate visuals take longer to load so it’s less frenzied.

I already have instruments from the original Rock Band, so I didn’t need to buy new ones for this game. The game’s developer, Harmonix, believe in instrument compatibility and it was good to find that I could dust off the Guitar Hero 3 controller (which has a nice clicky strum bar).

I don’t have many criticisms. Its the same Rock Band formula but I never expected anything more. I have to say the background information accompanying each unlocked photo is tricky to read, probably due to the Wii’s lack of high definition (and my lack of component cables). The end credits were also very long, unskippable and didn’t even have the backing of Beatles music (just lots of boring studio noise).

Overall it’s a well crafted music rhythm game that any Beatles fan will love.

New website design

September 11th, 2009

Crayons

My colourful new website design makes a change from the last one – you can see my previous designs over on the design page.

My starting point for this latest design was a blog post showing how to make abstract art with Illustrator. By using the twirl tool it’s possible to create some nice swirly effects, though I made sure not to get too carried away.

The new website design, viewed using a widescreen resolution

The new website design, viewed using a widescreen resolution

I wanted this design to be attention grabbing, so I wrote a jQuery script to make an animated TV screen effect. I used the Preload plugin, written by Ariel Flesler, to preload the images used by the TV. This means there’s no unsightly delay when changing between images, because the next one is already in the browser’s cache. Each image is loaded just before it’s needed, so the page isn’t bogged down with lots of concurrent image requests, which keeps everything fast.

Hiding Joomla’s author meta tag

September 9th, 2009

Joomla’s metadata is output by a simple jdoc statement from within the website’s template:

1
<jdoc:include type="head" />

When the template is up and running on a website that simple line will produce the relevant metadata in the HTML:

1
2
3
4
5
6
7
8
<base href="http://www.example.com/" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="robots" content="index, follow" />
<meta name="keywords" content="fun" />
<meta name="title" content="Welcome" />
<meta name="author" content="Joe Bloggs" />
<meta name="description" content="A great website" />
<meta name="generator" content="Joomla! 1.5 - Open Source Content Management" />

But sometimes you don’t want all of this metadata – in my case I didn’t want to output the author tag. As it turns out this is really simple to do because Joomla provides an in-built option, so there’s no coding changes required to the template. Great!

  1. Login as a super administrator.
  2. Go to “Site > Global Configuration” (or just click the big icon with that label):

    Accessing Joomla's Global Configuration

  3. In the “Metadata Settings” panel, at the bottom of the page, set “Show Author Meta Tag” to “No”:

    Hiding Joomla's author metadata

  4. Click the “Save” button in the top-right.

As you can see it’s also possible to hide the title meta tag in much the same way, should you want to.

Resizing images with jQuery

September 7th, 2009

jQuery

The other week I came across a post about resizing images with jQuery. The idea is simple: use JavaScript to detect the size of the browser window (or whatever metric works best for you) and then replace any images with smaller versions if needed.

My immediate thought was that this technique would work great on the splash page of the Insect Dynasty website that I worked on recently, since the splash image was slightly larger than I would’ve liked when viewed at 1024 x 768:

What a visitor would have seen at 1024 x 768

Before: what a visitor would have seen at 1024 x 768

Even though you really need to be using a higher resolution to view the artwork on the website easily I wasn’t happy to leave the splash page like this. Besides, I wanted to try this technique out. So I wrote an inline script for the splash page using jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
jQuery(document).ready(function() {

        // Switches between the small and large splash image as appropriate.
        function resizeSplash() {
       
            var $window = jQuery(window);
            var $body = jQuery("body");
            var $enter = jQuery("#enter");
           
            if ($window.height() < 750) {
                $body.css({
                    backgroundPosition: "center 0",
                    backgroundImage: "url('<?php bloginfo('template_url'); ?>/images/splash-background-small.jpg')",
                    minHeight: "0"
                });
                $enter.css("marginTop", "375px");
            } else {
                $body.removeAttr("style");
                $enter.removeAttr("style");
            }
        }

        // Initial call to image resizing.
        resizeSplash();

        // Resizes the splash image, if needed, when the visitor resizes their browser.
        jQuery(window).bind("resize", function() {
            resizeSplash();  
        }
       
    );

How it works

The key part of the script is where it checks if the browser viewport is less than 750 pixels tall – if so the background image on the body element is swapped. I also make some adjustments to the background-position and min-height properties, as these are also set in the stylesheet and need to be overridden as well when changing to a smaller splash image.

When the viewport height is 750 pixels or greater I simply remove the inline style attributes that jQuery would have set via calls to the css() function. This is the best way to revert back to using the larger splash image because it’s simple code, which is always a good thing – it makes the browser go back to using the rules from the stylesheet. That’s much better than making another call to css(), which would require duplicating bits of style definitions unnecessarily.

The technique relies on JavaScript being enabled so there may be some visitors who don’t enjoy its benefit. But it’s still an improvement for the people who do use JavaScript, as you can see:

With a smaller image the splash page fits nicely

After: with a smaller image the splash page fits nicely

The evil of splash pages

As an aside I’m aware that splash pages aren’t all that popular – they’re often just an unwanted obstacle for visitors, so there aren’t that many cases where I’d recommend using one on a website (not without really thinking it over carefully). In this case the splash page is partly setting the tone for the website and, being a website with a strong artistic focus, I consider the splash image to be part of the website’s content.

As splash pages go it’s also rather lightweight, unlike the frankly obnoxious ones you sometimes see which have heavyweight flash animations. That’s very difficult to pull off.

Getting the first frame of FLVs

September 4th, 2009

FFmpeg

Videos often look best when the first frame is visible before playback begins – they’re known as poster frames. But until playback begins the first frame won’t have been downloaded. So a technique to achieve the desired effect is to initially display a static thumbnail image taken from the very first frame of video. When playback begins this preview image will disappear and the video will seamlessly start playing in its place. It’s the technique that the popular JW FLV Player uses.

But how do you create a JPEG from the first frame of a flash video?

FFmpeg is a great little tool for the job, describing itself as a “cross-platform solution to record, convert and stream audio and video”.

Capturing the first frame of an FLV is then a simple command line using FFmpeg:

1
ffmpeg -i myvideo.flv -ss 0 -vframes 1 -vcodec mjpeg -f image2 preview.jpg

If you’re using Windows, like me, you’ll need to navigate your terminal to the directory where you extracted ffmpeg.exe, before running the command (unless you’ve gone ahead and added it to your system path variable).

You’ll also need to replace “myvideo.flv” with the name of the actual video you want to extract a picture from. You should either put the video in the same directory as FFmpeg or make sure to specify the appropriate path to it. If everything goes right you’ll find “preview.jpg” created in the same directory as FFmpeg.

In case you’re wondering, the various switches given to FFmpeg in the above command have the following meaning:

-i myvideo.flv
Specifies that “myvideo.flv” is the input file
-ss 0
Starts from this moment in the video; can be either whole seconds or hh:mm:ss[.xxx]
-vcodec mjpeg
Forces the video codec to mjpeg
-vframes 1
Extracts 1 frame of video
-f image2
Forces the output file format to image2
preview.jpg
Name of the output file

You’ll find a complete description of all the possible FFmpeg parameters in the FFmpeg documentation.

As you can see you’re not limited to extracting just the first frame of video – you can extract whatever you want. So you may well decide that some other frame is a better representation of the video (and might be more enticing to viewers).

Update: 8th September 2009

Jakob Nielsen has briefly touched on what makes a good video thumbnail in his article about how social media outsourcing can be risky. In it he looks at the Massachusetts Governor’s website and shows how poorly chosen thumbnails can make it difficult for users to differentiate between several videos. If you pick a boring thumbnail then don’t be surprised if people don’t watch the video.

In my case I needed to use the first frame as a thumbnail to create the impression of a talking-head coming to life. Nielsen also has an opinion on that as well – talking-head video is boring.

Cufon ignoring font colours

September 1st, 2009

Cufon Logo

Recently I was working on a website and using the rather natty Cufon (a clever bit of JavaScript) to do some font replacement. Or at least that was my intention – for some reason it was ignoring the font colour I’d set in my stylesheet…

Always add stylesheets before scripts

The problem was that I’d inadvertently linked my stylesheet into the page after the Cufon script, whereas styling should come before scripts. This is covered in Cufon’s styling documentation – by linking stylesheets into the page first you’re guaranteeing they’ll load before Cufon tries to replace any text. Do it the wrong way around and your style rules won’t necessarily be available by the time Cufon tries to work its magic.

This also explains why the problem was intermittent – in some cases the stylesheet must have been cached, which side-stepped the timing problems.

It’s good practice in general to link external stylesheets before external JavaScript files, as it can help your web pages to load faster. This is because web browsers won’t download subsequent resources once they find a script to download – scripts are capable of modifying the page, so the browser needs to download them fully before continuing. By putting other resources before the scripts they’ll be started first and will download in parallel (there’s a limit to how many files can download in parallel, but it’s nevertheless worth taking advantage of parallelism).

Fingerjig 1.3: jQuery on-screen keyboard

August 20th, 2009

Fingerjig

Fingerjig 1.3 is now available to play and it comes with a new feature that I think will particularly help players who are learning to type. I’ve had to restrict the new feature to Firefox only, so I’ll explain why I had to do that in a moment. For those of you who are using Firefox you’ll now see an on-screen keyboard directly beneath the game:

Fingerjig 1.3's shiny jQuery based on-screen keyboard

Fingerjig 1.3's shiny jQuery based on-screen keyboard

(Just to go off on a quick tangent: if you’re like me you might be wondering what “exsanguinating” means. The answer is “to be drained of blood” – how delightful. Now where was I…)

As you type the corresponding keys on the on-screen keyboard will light up, giving you an idea of where your fingers are. It’s a great aid when you’re starting out and trying to get your fingers onto the correct keys, as you shouldn’t have to look down so much. If you’re already a fast typer then you might just enjoy seeing the keys light up as your fingers whiz around the keyboard. I’m sure some players will find it distracting, so simply click the “close” link and it won’t bother you again. Simple.

Just for Firefox

And now to explain why the on-screen keyboard is only available for Firefox users. The reason is that I implemented it using jQuery, which is a great Javascript framework. Taking this approach allowed me to knock the keyboard together relatively quickly and I also found it fun to do. Unfortunately not all web browsers are equal and the performance of Javascript varies too much for this feature to work satisfactorily in other browsers, such as the all important Internet Explorer.

So that’s why I’ve reluctantly had to restrict the new feature to just Firefox. About 40% of visitors to this website use Firefox, which is quite respectable. But obviously I’d like to roll this feature out to the other 60% of visitors, so I’ll have to try and find some time to write a pure Flash version.

Play Fingerjig

Left 4 Dead survival map: Overworked

August 14th, 2009

Over the last couple of months I’ve spent some of my spare time creating a survival map for Valve Software’s zombie shooter, “Left 4 Dead”. The map is called “Overworked” and requires you to try and fend off the zombies from a couple of small office buildings.

If you get a chance to try it out then by all means let me know what you think, either by leaving a comment below or emailing me.

Screenshots

Download

Do you own a copy of L4D? You do? Great! You can download the Left 4 Dead map I created by clicking the link below:

Download "Overworked" (6.5 MB)

Installation

To install the map you need to…

1. Open “overworked.zip”, which you should be able to do by double-clicking it. If that doesn’t work then install a program like 7-Zip, which is free, and then try again.

2. Double-click “jm_overworked.vpk”, which you’ll find inside the zip file. If the installation worked then you’ll be told that the map was successfully installed and you’re now ready to play.

If the above didn’t work then you’ll need to extract “jm_overworked.vpk” from the zip file into Left 4 Dead’s “addons” folder, e.g. “C:\Program Files\steam\steamapps\common\left 4 dead\left4dead\addons”.