利用JavaScript进行图像处理的第一步是获取图像。这可以通过读取html文档里面的图像来完成。
首先,我们需要一个图像类来存储图像数据。这个图像类支持最基本的几个图像操作:新建图像,设置、取出像素点以及双线性插值采样。
function RGBAImage( w, h, data )
{
this.type = 'RGBAImage';
this.w = w;
this.h = h;
this.data = new Uint8Array(w*h*4);
data && this.data.set(data);
}
RGBAImage.prototype.getPixel = function(x, y) {
var idx = (y * this.w + x) * 4;
return new Color(
this.data[idx+0],
this.data[idx+1],
this.data[idx+2],
this.data[idx+3]
);
}
// bilinear sample of the image
RGBAImage.prototype.sample = function(x, y) {
var w = this.w, h = this.h;
var ty = Math.floor(y);
var dy = Math.ceil(y);
var lx = Math.floor(x);
var rx = Math.ceil(x);
var fx = x - lx;
var fy = y - ty;
var c = this.getPixel(lx, ty).mul((1-fy) * (1-fx))
.add(this.getPixel(lx, dy).mul(fy * (1-fx)))
.add(this.getPixel(rx, ty).mul((1-fy) * fx))
.add(this.getPixel(rx, dy).mul(fy * fx));
c.clamp();
return c;
};
RGBAImage.prototype.setPixel = function(x, y, c) {
var idx = (y * this.w + x) * 4;
this.data[idx] = c.r;
this.data[idx+1] = c.g;
this.data[idx+2] = c.b;
this.data[idx+3] = c.a;
};
此外我们还需要一个颜色类,用于进行基本的颜色操作。
function Color(r, g, b, a)
{
if( arguments.length !== 4 )
{
th