phoboslab/Ejecta — pull request #260 by doctb (2013-12-21 12:15:54+00:00)
Title: * Data URI support for image source.

Hi!

I was in need of Data URI support for images src so I've implemented it.
I think this is very handy and allows Ejecta to be even closer to HTML5 specifications.

I am not very familiar with Obj-C so please let me know if there is anything I did wrong or that I can do better.

Here are the things I changed:

1. In EJTexture: moved outside of _**loadPixelsFromPath**_ the code to load pixels from an UIImage, into a new method called _**loadPixelsFromUIImage**_.

2. In EJTexture: added a static method to identify if a path (basically what the user set in image's .src) is really a file path or is a Data URI string. Method named _**isDataURI**_.

3. Using this method in EJBindingImage to avoid prepending the device "path to resource" if this path is in fact not a file, but a Data URI string.

4. In EJTexture's _**cachedTextureWithPath**_: if the path is in fact a Data URI string, we don't want to use the string itself as cache key because this string may be super huge. In this case, using instead it's sha1 hash. Added for this purpose a static inline _**NSStringCCHashFunction**_ from https://github.com/hypercrypt/NSString-Hashes/blob/master/NSString%2BHashes.m (public domain license) because the default Obj-C string hash value seems to be very bad and to have more collisions issues than any other hashing algorithm.

5. Finally, in _**loadPixelsFromPath**_: if the path is a Data URI we create the UIImage from this data (simple 3 liner) else the UIImage is created the same way as before. And then obviously, calls the _**loadPixelsFromUIImage**_ method (cf point 1).

Here is a very small example to test it out:

```
var w = window.innerWidth;
var h = window.innerHeight;
var canvas = document.getElementById('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');

// Small red dot image. For a better example, use an online service to generate Data URI from a picture.
// (for example Google first answer with "picture to data uri" search)
var imageData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

var img = new Image();
img.onload = function() {
console.log('Image loaded. Size is ' + this.width + ' x ' + this.height);
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, w, h);
ctx.drawImage(this, 0, 0);
};

img.src = imageData;
```

Thank you in advance for having a look to this PR!
If we everything is going well with it, I will next PR an EJBindingImagePicker I did to pick pictures from the photo roll :smile:.

ps: I just noticed there was another PR opened for the same feature: #241.
It would be great if you could merge one or the other!! :smile: