如何在图块中划分图像?

代言人

我必须完成以下任务:

将图像划分为小块,计算每个小块的平均颜色,从服务器获取该颜色的小块,然后将结果合成为原始图像的光马赛克。

最佳策略是什么?我想到的第一个解决方案是使用画布。

盲人67

一种获取像素数据和查找图块均值的简单方法。该代码将需要更多检查,以检查图像尺寸是否可以除以切片数。

var image = new Image();
image.src = ??? // the URL if the image is not from your domain you will have to move it to your server first

// wait for image to load
image.onload = function(){
    // create a canvas
    var canvas = document.createElement("canvas");
    //set its size to match the image
    canvas.width = this.width;
    canvas.height = this.height;
    var ctx = canvas.getContext("2d"); // get the 2d interface
    // draw the image on the canvas
    ctx.drawImage(this,0,0);
    // get the tile size
    var tileSizeX = Math.floor(this.width / 10);
    var tileSizeY = Math.floor(this.height / 10);
    var x,y;
    // array to hold tile colours
    var tileColours = [];
    // for each tile
    for(y = 0; y < this.height; y += tileSizeY){
        for(x = 0; x < this.width; x += tileSizeX){
            // get the pixel data
            var imgData = ctx.getImageData(x,y,tileSizeX,tileSizeY);
            var r,g,b,ind;
            var i = tileSizeY * tileSizeX; // get pixel count
            ind = r = g = b = 0;
            // for each pixel (rgba 8 bits each)
            while(i > 0){
                // sum the channels
                r += imgData.data[ind++];
                g += imgData.data[ind++];
                b += imgData.data[ind++];
                ind ++;
                i --;
            }
            i = ind /4; // get the count again
            // calculate channel means
            r /= i;
            g /= i;
            b /= i;
            //store the tile coords and colour
            tileColours[tileColours.length] = {
                rgb : [r,g,b],
                x : x,
                y : y,
            }
        }
        // all done now fetch the images for the found tiles.
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章