Last active
November 16, 2018 19:12
-
-
Save duhaime/b245fbcb9ec5b52cc8b789847b313185 to your computer and use it in GitHub Desktop.
Pixelate Image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset='UTF-8'> | |
<title>title</title> | |
</head> | |
<body> | |
<div id='images'> | |
<img src='img.jpg' onload='init()' > | |
</div> | |
<input type='range' | |
id='box-size' | |
name='volume' | |
min='1' | |
max='10'> | |
<script> | |
var img, | |
canvas, | |
ctx, | |
width, | |
height; | |
function getMean(vals) { | |
return vals.reduce(function(sum, i) { | |
sum += i; return sum; | |
}) / vals.length; | |
} | |
function getMedian(vals) { | |
vals.sort(function(i, j) { return i > j }); | |
return vals[ parseInt(vals.length/2) ] | |
} | |
function init() { | |
img = document.querySelector('img'); | |
canvas = document.createElement('canvas'); | |
ctx = canvas.getContext('2d'); | |
width = img.width; | |
height = img.height; | |
draw(); | |
} | |
function draw() { | |
var box = parseInt(document.querySelector('#box-size').value); | |
// initialize the canvas | |
canvas.width = width; | |
canvas.height = height; | |
ctx.drawImage(img, 0, 0, width, height); | |
document.querySelector('#images').appendChild(canvas); | |
// find the dominant hue in each block size | |
for (var x=0; x<Math.ceil(width/box); x++) { | |
for (var y=0; y<Math.ceil(height/box); y++) { | |
var vals = ctx.getImageData(x*box, y*box, box, box).data; | |
var mean = parseInt( getMean(vals) ); | |
ctx.fillStyle = 'rgba(' + mean + ',' + mean + ',' + mean + ', 255)'; | |
ctx.fillRect(x*box, y*box, box, box); | |
} | |
} | |
} | |
document.querySelector('#box-size').addEventListener('change', draw) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment