图像转ASCII码

http://www.cnblogs.com/jelly5203/p/5589295.html
代码实现html5文件夹中

<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Title</title>
</head>
<style type=“text/css”>
span{
letter-spacing: 0.5em;
}
</style>
<body>

<canvas id=“canvas”></canvas>
<script>
var canvas = document.getElementById(“canvas”);
var context = canvas.getContext(“2d”);
canvas.width = 800;
canvas.height = 800;
var img = new Image();
img.src = “chudao.jpg”;
img.onload =function(){
invert(this);
};
// 像素点的rgba数组
// function invert(img) {
// context.drawImage(img,0,0);
// //获取图片对象以及元素点的数组
// var img1 = context.getImageData(0, 0, 800, 800);
// var data = img1.data;
// //反转rgba
// /for (var i = 0, len = data.length; i < len; i += 4) {
// data[i]=255-data[i];
// data[i+1]=255-data[i+1];
// data[i+2]=255-data[i+2];
// }/
// for (var i = 0, len = data.length; i < len; i += 4) {
// var avg=(data[i]+data[i+1]+data[i+2])/3;
// data[i]=avg;
// data[i+1]=avg;
// data[i+2]=avg;
// }
// context.putImageData(img1, 0, 0);
// }

function invert(img) {
context.drawImage(img,0,0);
//获取图片对象以及元素点的数组
var img1 = context.getImageData(0, 0, 300, 300);
var data = img1.data;
//转换灰度图
var arr=[“M”,“N”,“H”,“Q”,“$”,“O”,“C”,,,,,,“–”,,];
var result=[];
for (var i = 0, len = data.length; i < len; i += 8) {
var avg=(data[i]+data[i+1]+data[i+2])/3;
var num=Math.floor(avg/18);
result.push(arr[num]);
if(i%1200==0&&i!=0){
result.push(“<br>”)
}
}

var opt = document.createElement(“span”);

opt.innerHTML=result.join();
document.body.appendChild(opt);
}
</script>
</body>
</html>
QQ截图20161004112112.png
QQ截图20161004112252.png