Built with blockbuilder.org
forked from sxywu‘s block: Image processing fun #1
forked from sxywu‘s block: Image processing fun #2
forked from sxywu‘s block: Image processing fun #3
forked from sxywu‘s block: Image processing fun #4
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
</style>
</head>
<body>
<img src="https://pbs.twimg.com/profile_images/3775316964/fe2ba0b0a4f0fb30aaef37c089553a8d.jpeg" width="400" />
<canvas id="canvas"></canvas>
<script>
d3.json('twitter_profile.json', function(image) {
var imageSize = Math.sqrt(image.length);
var scaleFactor = Math.floor(500 / imageSize);
var canvas = document.getElementById('canvas');
canvas.width = imageSize * scaleFactor;
canvas.height = imageSize * scaleFactor;
var ctx = canvas.getContext('2d');
var data = [];
var threshold = 122.5;
// turn it grayscale first
_.each(image, function(pixel) {
data.push(Math.max(pixel[0], pixel[1], pixel[2]));
});
// Atkinson dithering
_.each(data, function(oldPixel, i) {
var newPixel = oldPixel > threshold ? 255 : 0;
var error = (oldPixel - newPixel) >> 3;
data[i] = newPixel;
data[i + 1] += error;
data[i + 1] += error;
data[i + imageSize - 1] += error;
data[i + imageSize] += error;
data[i + imageSize + 1] += error;
data[i + imageSize + 2] += error;
});
data = data.slice(0, imageSize * imageSize);
var imageData = ctx.getImageData(0,0,imageSize * scaleFactor, imageSize * scaleFactor);
_.each(data, function(pixel, i) {
_.times(scaleFactor, function(x) {
_.times(scaleFactor, function(y) {
// first calculate row, then column
var index = Math.floor(i / imageSize) * (imageSize * Math.pow(scaleFactor, 2)) +
(y * imageSize * scaleFactor) +
((i % imageSize) * scaleFactor + x);
index *= 4;
imageData.data[index] = pixel;
imageData.data[index + 1] = pixel;
imageData.data[index + 2] = pixel;
imageData.data[index + 3] = 255;
});
});
});
console.log(imageData)
ctx.putImageData(imageData, 0, 0);
});
</script>
</body>