Skip to content

Instantly share code, notes, and snippets.

@DC3
Created August 31, 2017 10:14
Show Gist options
  • Save DC3/5b53ed9e41e652f07846870e91ea23cf to your computer and use it in GitHub Desktop.
Save DC3/5b53ed9e41e652f07846870e91ea23cf to your computer and use it in GitHub Desktop.
test-get-all-pixel-hex.coffee
testImgUrl = '//img.alicdn.com/tps/i4/TB1PVZoOpXXXXcKXXXXSutbFXXX.jpg'
rgbToHex = (r, g, b) ->
hex = (i) ->
h = i.toString 16
h = '0' + h if h.length < 2
h
['#', hex(r), hex(g), hex(b)].join('')
getOnePixelHex = (context, x, y, w = 1, h = 1) ->
c = context.getImageData(x, y, w, h).data
hex = rgbToHex c...
hex
createCanvas = (width, height) ->
group = "createCanvas width=#{width} height=#{height}"
console.time group
canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
context = canvas.getContext('2d')
console.timeEnd group
{canvas, context}
drawImage = (target, img, sw = 0) ->
isScale = !!sw
{ canvas, context } = target
group = "drawImage scale=#{isScale}"
console.time group
if isScale
sh = parseInt(sw / img.width * img.height, 10)
canvas.setAttribute 'width', sw
canvas.setAttribute 'height', sh
console.log 'drawImage scale',
{imgWidth: img.width, imgHeight: img.height, sw, sh}
context.drawImage img, 0, 0, img.width, img.height, 0, 0, sw, sh
else
context.drawImage img, 0, 0
console.timeEnd group
loadImage = (url) ->
img = new Image()
img.crossOrigin = 'anonymous'
new Promise (res, rej) ->
img.onload = res.bind(null, img)
img.onerror = rej
img.src = url
loadImage(testImgUrl).then (img) ->
{width, height} = img
console.log 'loadImage done', {width, height}
ref = createCanvas(width, height)
drawImage(ref, img)
#scale
#drawImage(ref, img, 500)
console.time 'get one pixel hex'
hex = getOnePixelHex(ref.context, 0, 0)
console.log {hex}
console.timeEnd 'get one pixel hex'
console.time 'get all imgData'
imgData = ref.context.getImageData(0, 0, width, height)
console.timeEnd 'get all imgData'
console.time '8bit'
b8 = new Uint8Array(imgData.data.buffer)
console.timeEnd '8bit'
console.time 'get all pixel hex'
dict = {}
maxHex = null
for i in [0...b8.length / 4]
#for i in [0...10]
hex = rgbToHex(b8.slice(i*4, (i+1) * 4)...)
dict[hex] or= 0
maxHex or= hex
++dict[hex]
if hex isnt maxHex and dict[hex] > dict[maxHex]
maxHex = hex
console.timeEnd 'get all pixel hex'
console.log {maxHex}
window.b8 = b8
window.dict = dict
return
# get top 10 hex
###_.chain(dict)
.map((count, hex) => { return {hex, count}; })
.sortBy(['count']).takeRight(10).value()###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment