Earlier today I discovered the excellent Color Thief JavaScript library by Lokesh Dhakr. Color Thief gives you the ability to find the dominant color of a picture, or a palette of major colors. Check the site for examples. I thought it would be interesting to wrap this into a PhoneGap project and create palettes based on your camera. Here's what I came up with.
First off, if you've never looked at PhoneGap's Camera API, it's worth taking a quick peak at their documentation. The basics you should be aware of is that PhoneGap can work with either new pictures taken with the camera or existing ones saved to the device. You can control height, width, quality, and how the data is handed over to you.
I began by working with two buttons - one to let you take a new picture and one to let you select an existing one.
<input type="button" id="takePictureBtn" value="Take Picture">
<input type="button" id="picPictureBtn" value="Select Picture">
These buttons then were hooked up with event listeners:
$("#takePictureBtn").click(takePic);
$("#picPictureBtn").click(selectPic);
function takePic(e){
navigator.camera.getPicture(picSuccess, picFail, {quality:75, targetWidth:desiredWidth, targetHeight:desiredWidth, sourceType:Camera.PictureSourceType.CAMERA, destinationType:Camera.DestinationType.FILE_URI});
}
function selectPic(e) {
navigator.camera.getPicture(picSuccess, picFail, {quality:75, targetWidth:desiredWidth, targetHeight:desiredWidth, sourceType:Camera.PictureSourceType.PHOTOLIBRARY, destinationType:Camera.DestinationType.FILE_URI});
}
In both cases, the picture's file URI is sent to a success handler. I simply then assign that to an empty image:
function picSuccess(imageURI) {
$("#yourimage").attr("src",imageURI);
}
Now for the fun part. The Color Thief API is rather simple, but when I switched from a static image to a dynamic one, I noticed I ran into errors. Turns out - I was trying to run the code before the image was fully loaded. I therefore added a new event listener:
$("#yourimage").load(getSwatches);
The getSwatches function then will handle getting the color palette and assigning them to a set of swatches below the image:
function getSwatches(){
var colorArr = createPalette($("#yourimage"), 5);
for (var i = 0; i < Math.min(5, colorArr.length); i++) {
$("#swatch"+i).css("background-color","rgb("+colorArr[i][0]+","+colorArr[i][1]+","+colorArr[i][2]+")");
}
}
And the results? Here are some samples:
I've included a zip of the project below. You will find the code in the assets folder and an APK in the bin folder.