Skip to content

Instantly share code, notes, and snippets.

@fuba
Forked from cxx/decode_kanji_image.user.js
Created May 20, 2011 21:35
Show Gist options
  • Save fuba/983873 to your computer and use it in GitHub Desktop.
Save fuba/983873 to your computer and use it in GitHub Desktop.
~/.js/twitter.com.js
var showImage = function () {
$('.tweet-text', document.body).each(function(index, elem) {
if ($('canvas', elem).length > 0) return;
var match = elem.textContent.match(/(k-host\.appspot\.com\/)?([\u4e00-\u8dff]{109,124})/);
if (!match) return;
var text = match[2];
var cols = 18;
var scale = 16;
var dataLen = text.length;
var bodyLen = (cols / 3) * cols;
var paletteLen = dataLen - bodyLen;;
var data = [];
for (var i = 0; i < dataLen; i++)
data.push(text.charCodeAt(i) - 0x4e00);
var palette = data.slice(0, paletteLen).map(function(val) {
var r = val >> 9 << 3;
var g = ((val >> 4) & 0x1f) << 3;
var b = (val & 0x0f) << 4;
r += r >> 5; g += g >> 5; b += b >> 4;
return 'rgb('+[r, g, b].join(', ')+')';
});
var $canvas = $('<canvas>').attr('width', cols*scale).attr('height', cols*scale);
$(elem).append($('<p>').append($canvas));
var canvas = $canvas.get(0);
var ctx = canvas.getContext('2d');
ctx.scale(scale, scale);
var comment = [];
var commentLen = parseInt(bodyLen / 8) * 8;
i = 0;
data.slice(paletteLen).forEach(function(val) {
for (var j = 8; j >= 0; j -= 4, i++) {
ctx.fillStyle = palette[(val >> j) & 0x0f];
ctx.fillRect(parseInt(i%cols), parseInt(i/cols),1,1);
}
comment.push(val >> 12)
});
if (match[1]) {
var a = $('<a>').attr('href', 'http://'+match[0]).attr('target', '_blank').text(match[0]);
$(elem).contents().eq(0).replaceWith(a);
}
if (comment.some(function(n) { return n > 0; })) {
var commentStr = '';
while (comment.length >= 8) {
var n = 0;
for (i = 0; i < 8; i++)
n = (n << 2) | comment.shift();
commentStr += String.fromCharCode(n);
}
$(elem).append($('<p>').css('font-size', '100px').text(commentStr));
}
});
};
document.addEventListener('DOMNodeInserted', showImage, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment