How to Validate Image URL Prior to Loading: More Learnings from Flash and Twitter Project

by carl schooff on April 15, 2011 · View Comments

in seminar

Ok, now that you’ve seen the trouble I had with Loading XML from Twitter, I’m going to talk a bit about making sure the images you try to load have valid file names. This trick can come in handy for many things.

See the TwitterSpitter Applet in Action.

Watch the Video Explanation

Validate Filenames Prior to Loading

Even though LoaderMax’s ImageLoader and the AS3 Loader Object can report errors after they’ve attempted to load an external asset, there is no point in wasting the resources/bandwidth of trying to load an asset that you know is going to fail.

Although the normal AS3 Loader object does a find job of reporting errors when it attempts to load something, I don’t like all the extra steps of having to:
-use addEventListener for every event I want to respond to
-create formal URLRequests for each loader
-deal with creating a routine to sequentially load and track each asset

For this project I was relying on GreenSock’s LoaderMax to do all the dirty work for me. LoaderMax allows you to load many different asset types through it’s ImageLoader, SWFLoader, XMLLoader, VideoLoader and other loaders while easily tracking the loading progress of each item and the cumulative load progress. All this with VERY little code. After using LoaderMax on one project I will never use the built-in AS3 stuff again. ever. Just take a look at how easy loading a single image is and all the properties you can set with an ImageLoader.

//create an ImageLoader:
 var loader:ImageLoader = new ImageLoader("img/photo1.jpg", {name:"photo1",
        container:this, x:180, y:100,
        width:200, height:150,
        centerRegistration:true,
        onComplete:onImageLoad}
);

 //begin loading
 loader.load();

 //when the image loads, fade it in from alpha:0 using TweenLite
 function onImageLoad(event:LoaderEvent):void {
  TweenLite.from(event.target.content, 1, {alpha:0});
 }

Using LoaderMax.parse() to load a MASSIVE array of images
The problem I discus in the video has to do with the fact that I was using LoaderMax’s parse() method which takes an array of multiple URLs and creates the appropriate loaders for me and then loads all the assets.
It knows what types of Loaders to create based on the file extensions. So if you do something like this:

var assets:Array = ["lightning.flv, "loud.mp3", "hamsterdance.gif", "strongbad.swf"]

var queue:LoaderMax = LoaderMax.parse(assets, {onComplete:completeHandler});
queue.load();

LoaderMax will create these types of Loaders in the following order:
VideoLoader
MP3Loader
ImageLoader
SWFLoader

And then load them all perfectly and fire the completeHandler callback when done. It works like a charm.

For my TwitterSpitter, I simply create an array out of all the nodes from my Twitter xml and pass it into LoaderMax.parse. I load 100 images with just a few lines of code and I don’t have to worry about checking if they are all loaded or looping through 100 different objects. It all happens behind the scenes for me.

Twitter’s Lenient File Naming Restrictions Cause Much Trouble

Since LoaderMax.parse() needs to figure out what Loaders to create based on the file extension, I ran into trouble when Twitter told me it had to load images with the following names:

jennyrose_normal
hal_the_barber.bmp
johnny_2_times.JPE
someJerk.jpg.normal.rem

As you can see the above examples are either missing an extension or have extensions that aren’t normal image extensions. LoaderMax is expecting GIF, PNG, JPG, or JPEG in order to detect an ImageLoader is necessary. LoaderMax would instantly fire a run-time error as it couldn’t do anything with the garbage I was passing in.

Regular Expressions to the Rescue

In order to validate that the asset I wanted to load had a properly formatted image extension I decided to use a Regular Expression. A regular expression allows you to create a pattern to search for using a seemingly cryptic string of character codes. Wikipedia offers some nice examples of things you can test:

The sequence of characters “car” appearing consecutively in any context, such as in “car”, “cartoon”, or “bicarbonate”
The sequence of characters “car” occurring in that order with other characters between them, such as in “Icelander” or “chandler”
The word “car” when it appears as an isolated word
The word “car” when preceded by the word “blue” or “red”
The word “car” when not preceded by the word “motor”
A dollar sign immediately followed by one or more digits, and then optionally a period and exactly two more digits (for example, “$100″ or “$245.99″).*

Using A Regular Expression to test if a file name contains a valid file extension.

I’m no regexp genius so I used Grant Skinner’s RegExr Tool to grab a freebie. Its no fault of the tool, but I didn’t find exactly what I needed. There are many great regexps in there!

My first regexp only tested if the file name CONTAINED .jpg .gif .png and looked something like this:

/[.](jpeg)|(jpg)|(gif)|(png)$/

so the following filenames would validate:
something.jpg
cuteCat.png
ateTooMuch.gif

The following filenames would fail:
something
cuteCat.jpe
ateTooMuch.bmp

Looks good, right? Wrong. The trouble was that the following capitalized extensions would fail the test

something.JPG
cuteCat.PNG

Yeah I could hack in the uppercase patterns, but there was a test that failed that was much more serious.

I noticed a few Twitter users had profile image filenames like

doug.jpg_normal.rem

As you can see the above string DOES contain “.jpg” but its not at the end! This caused me way too much unexpected trouble.

Fortunately I came across a regular expression that suited all my needs of making sure that uppercase or lowercase instances of .jpg .png .gif and .jpeg need to be the last items in a string and not somewhere in the middle. This expression looked like: /(?i)\.(jpg|png|gif|jpeg)$/ and can be found at stackoverflow.com

Paste this AS3 code into a blank FLA to Test a RegExp

//create regexp
var validImageRegExp:RegExp =/(?i)\.(jpg|png|gif|jpeg)$/

//these strings are valid and pass the test:
//they will output : true
trace(validImageRegExp.test("something.jpg"))
trace(validImageRegExp.test("something.JPG"))
trace(validImageRegExp.test("something.JPEG"))

//these strings are not valid and fail the test:
//they will output : false
trace(validImageRegExp.test("something.bmp"))
trace(validImageRegExp.test("something.jpe"))
trace(validImageRegExp.test("something"))
trace(validImageRegExp.test("something.jpg.crappy.rem"))

So there you have it. One little thing like filename validation cost me a few hours of testing and fortunately some learning. I never would have guessed that Twitter would have so many unconventional filenames that break what most would consider “standard web naming conventions”. Chances are if you are loading assets within your realm of control you would have validated the filenames PRIOR to uploading, but whenever you are dealing with third-party tools, you never know what to expect.

Other Articles In This Series

-Intro to the TwitterSpitter and common errors when loading XML data from Twitter
-Loading assets from other domains via a php proxy
-Dealing with Twitter’s rate limit

Post to Twitter Post to Facebook

  • http://www.snorkl.tv/2011/04/massive-learning-experiences-from-working-with-flash-and-twitter-api-loading-xml-data-from-twitter/ Massive Learning Experiences from Working with Flash and Twitter API: Loading XML Data From Twitter

    [...] -Detecting illegal image names prior to loading -Loading assets from other domains via a php proxy -Dealing with Twitter’s rate limit [...]

  • MH

    Awesome! Thanks!

  • http://www.snorkl.tv/2011/04/get-data-into-flash-from-other-domains-with-crossdomain-xml-or-php-proxy-script/ Get Data into Flash from Other Domains with CrossDomain.xml or PHP Proxy Script

    [...] to the TwitterSpitter and common errors when loading XML data from Twitter -Detecting illegal image names prior to loading -Loading assets from other domains via a php proxy -Dealing with Twitter’s rate [...]

  • http://www.snorkl.tv/2011/04/understanding-the-twitter-rate-limit-and-how-it-can-impact-your-flash-apps/ Understanding the Twitter Rate Limit and How it can Impact Your Flash Apps

    [...] to the TwitterSpitter and common errors when loading XML data from Twitter -Detecting illegal image names prior to loading -Loading assets from other domains via a php [...]

blog comments powered by Disqus

Previous post:

Next post: