f8g

ImageData callback

イマドキなデータのやりとり。

server.php

<?php
$q = str_split($_GET["q"]);

$data = array();

foreach($q as $c){
	$n = ord($c);

	if($n > 255){
		exit("cannot support charactor '" . $c . "'");
	}
	else{
		$data[] = $n;
	}
}

$v_n = count($data);
$px_n = ceil($v_n / 3);
$img = imagecreate($px_n, 1);
$i = 0;
$x = 0;

while($x < $px_n){
	$px = imagecolorallocate(
		$img,
		array_key_exists($i++, $data) ? $data[$i - 1] : 0,
		array_key_exists($i++, $data) ? $data[$i - 1] : 0,
		array_key_exists($i++, $data) ? $data[$i - 1] : 0
	);

	imagesetpixel($img, $x++, 0, $px);
}

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>

client.html

<html>
<head>
<title>client</title>
</head>
<body>
<canvas></canvas>
<script type="text/javascript">
var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");

var data = {a: 1, b: 2, c: 3};
var img = new Image;

img.onload = function(){
	var w = canvas.width = img.naturalWidth;
	var h = canvas.height = img.naturalHeight;
	context.drawImage(img, 0, 0);
	var data = context.getImageData(0, 0, w, h).data;
	console.log(ImageDataToData(data));
};

img.src = "server.php?q=" + encodeURIComponent(JSON.stringify(data));

function ImageDataToData(data){
	var d = [data[i] for(i in data) if((i * 1 + 1) % 4 && data[i])];
	var str = String.fromCharCode.apply(null, d);
	return JSON.parse(str);
}
</script>
</body>
</html>

利点なし。