Image to Byte Array

Here is a small fiddle that I've done to convert images to byte array.
I use it to create icons for my projects with Arduino and similar.

The code is a mess but the part that convert the image is pretty simple. Using the Canvas object I was able to get the pixels of the image.
The getPixelData() gives you back an array formatted in this way:

  var pixelarray = [pixel1GreenVal, pixel1RedVal, pixel1BlueVal, pixel1AlphaVal,...];

I've cycled the array in steps of 4, getting the average value of the colors (greyscale filter), and using a threshold value I converted the image to monochrome (B/W).

...
var threshold = document.getElementById('threshold').value;
elem = document.getElementById('canvas')
context = elem.getContext('2d')
var img = context.getImageData(0,0,canvas.width,canvas.height)
var threshold = document.getElementById('threshold').value;
for(var i=0; i<img.data.length;i=i+4){    
  var avg = (img.data[i]+img.data[i+1] + img.data[i+2])/3
  if(avg>threshold){
    img.data[i] = 255 
    img.data[i+1] = 255 
    img.data[i+2] = 255        
  }else{
    img.data[i] = 0 
    img.data[i+1] = 0
    img.data[i+2] = 0        
  }
}
var elem = document.getElementById("canvas2");
elem.width=img.width;
elem.height=img.height;
var ctx = elem.getContext("2d");
ctx.putImageData(img,0,0)  
...

from this point on, creating the array with 0 and 1 and converting it to a string was trivial.

for(var i=0; i<img.data.length;i=i+4){    
   var avg = (img.data[i]+img.data[i+1] + img.data[i+2])
   if(avg>threshold) str.push(0)
     else str.push(1)
}
var s = 'static const unsigned char PROGMEM changeMe[] ={B';
for(var i=0;i<str.length;i++){   
   if(i!=0 && i%8==0) s+=', B'
   s+=str[i]    
}
s+='};'

JS Bin on jsbin.com

With the same process is possible also to make a beautiful ASCII webcam :)

Here are some examples:

PHOTO

ICONS

Davide Andreazzini

Read more posts by this author.