Skip to content

Instantly share code, notes, and snippets.

@radiodario
Forked from kevincennis/img2table.js
Created February 27, 2013 22:45
Show Gist options
  • Save radiodario/5052555 to your computer and use it in GitHub Desktop.
Save radiodario/5052555 to your computer and use it in GitHub Desktop.
function img2table( img ){
var canvas = document.createElement('canvas')
, ctx = canvas.getContext('2d')
, table = document.createElement('table')
, width = canvas.width = img.width
, height = canvas.height = img.height
, pixels
, i, j, l1, l2
, tr, td, r, g, b
table.width = width + 'px'
table.height = height + 'px'
table.cellPadding = '0'
table.cellSpacing = '0'
ctx.drawImage(img, 0, 0, width, height)
pixels = ctx.getImageData(0, 0, width, height)
for ( i = 0, l1 = pixels.data.length; i < l1; ){
tr = document.createElement('tr')
for ( j = i, l2 = i + width * 4; j < l2; j+= 4 ){
td = document.createElement('td')
r = pixels.data[j]
g = pixels.data[j+1]
b = pixels.data[j+2]
td.style.backgroundColor = '#' + r.toString(16) + g.toString(16) + b.toString(16)
td.width = '1px'
td.height = '1px'
tr.appendChild(td)
}
table.appendChild(tr)
i = j
}
return table
}
var img = document.createElement('img')
img.src = 'http://somedomain.com/path/to/image.jpeg'
img.onload = function(){
document.body.appendChild(img2table(img))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment