Skip to content

Instantly share code, notes, and snippets.

@masawada
Forked from KOBA789/mstrFilter.js
Created February 16, 2014 02:57
Show Gist options
  • Save masawada/9028615 to your computer and use it in GitHub Desktop.
Save masawada/9028615 to your computer and use it in GitHub Desktop.
var mstrFilter = (function () {
function applyFilter (ctx, img, scale) {
var TRIM_THRESHOLD = 10000,
R_RATIO = 1.0,
G_RATIO = 0.97,
B_RATIO = 0.95,
CONTRAST = 1.1,
K = 1.2;
var w = ~~(img.width * scale), h = ~~(img.height * scale),
w4 = w*4;
ctx.drawImage(img, 0, 0, w, h);
var srcData = ctx.getImageData(0, 0, w, h),
src = srcData.data,
dstData = ctx.getImageData(0, 0, w, h),
dst = dstData.data,
i = 0,
threshold = w * h / TRIM_THRESHOLD,
reduction = 0,
ratio = 1.0,
histgram = new Uint32Array(256),
max = function (a, b, c) { return a >= b ? (a >= c ? a : (b >= c ? b : c)) : (b >= c ? b : c); },
c = 0,
a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0, a6 = 0, a7 = 0, a8 = 0;
for (i = 0; i < src.length; i += 4) {
histgram[max(src[i], src[i+1], src[i+2])] += 1;
}
for (i = 255; i >= 0; --i) {
if (threshold >= histgram[i]) {
++reduction;
} else {
break;
}
}
ratio = 255 / (255 - reduction);
for (i = 0; i < src.length; i += 4) {
src[i ] = (((src[i ] * ratio * R_RATIO) - 127) * CONTRAST) + 127;
src[i+1] = (((src[i+1] * ratio * G_RATIO) - 127) * CONTRAST) + 127;
src[i+2] = (((src[i+2] * ratio * B_RATIO) - 127) * CONTRAST) + 127;
}
c = 2;
for (i = w4 + 4; i < src.length - w4 - 4; i += 4) {
if (c >= w) { c = 2; i += 4; continue; }
a1 = i-w4;
a0 = a1-4;
a2 = a1+4;
a4 = i;
a3 = a4-4;
a5 = a4+4;
a7 = i-w4;
a6 = a7-4;
a8 = a7+4;
dst[i ] = (1+8*K/9) * src[a4 ] + -K * (src[a0 ] + src[a1 ] + src[a2 ] + src[a2 ] + src[a5 ] + src[a6 ] + src[a7 ] + src[a8 ])/9;
dst[i+1] = (1+8*K/9) * src[a4+1] + -K * (src[a0+1] + src[a1+1] + src[a2+1] + src[a2+1] + src[a5+1] + src[a6+1] + src[a7+1] + src[a8+1])/9;
dst[i+2] = (1+8*K/9) * src[a4+2] + -K * (src[a0+2] + src[a1+2] + src[a2+2] + src[a2+2] + src[a5+2] + src[a6+2] + src[a7+2] + src[a8+2])/9;
++c;
}
ctx.putImageData(dstData, 0, 0);
}
function mstrFilter (query) {
var $imgs = document.querySelectorAll(query);
[].slice.call($imgs).forEach(function ($img) {
var $canvas = document.createElement('canvas'),
scale = window.devicePixelRatio || 1;
$canvas.width = $img.width * scale;
$canvas.height = $img.height * scale;
$canvas.style.width = $img.width + 'px';
$canvas.style.height = $img.height + 'px';
$canvas.style.display = 'none';
$img.parentElement.insertBefore($canvas, $img.nextSibling);
applyFilter($canvas.getContext('2d'), $img, scale);
$img.style.display = 'none';
$canvas.style.display = 'block';
});
}
return mstrFilter;
})();
/* EXAMPLE:
window.addEventListener('load', function () {
mstrFilter('.meshi_photo_main > img');
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment