javascript - 如何将图像分割成图 block ?

标签 javascript html image web html5-canvas

我必须完成以下任务:

divides the image into tiles, computes the average color of each tile, fetches a tile from the server for that color, and composites the results into a photomosaic of the original image.

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

最佳答案

获取像素数据并查找图 block 平均值的简单方法。对于尺寸无法除以图 block 数量的图像,代码需要进行更多检查。

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.
    }

关于javascript - 如何将图像分割成图 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38156779/

相关文章:

javascript - 如何在 native react 中为按钮设置计时器?

html - 当背景图片顶部有元素时缩放

javascript - 为什么在jsfiddle中显示ReferenceError : function is not defined?

javascript - 将 Summernote 与 Meteor 结合使用(发现 Meteor)

JavaScript 删除 IIFE 事件监听器

javascript - 如果为空则更改输入样式

javascript - JSON.stringify 忽略一些对象成员

Javascript 将动态图像从 URL 绘制到 Canvas 元素上

javascript调整图像大小[缩小尺寸]并上传

javascript - 将图像放入数组并显示它们