Build 2D Array of Canvas RGB values

自作多情 提交于 2019-12-07 20:09:45

问题


I'm trying to send a 2D array of RGB values to PHP from the array of values from the getImageData().data method:

for (var i=0;i<imgData.data.length;i+=4){

    // If you want to know the values of the pixel
    var r = imgData.data[i + 0];
    var g = imgData.data[i + 1];
    var b = imgData.data[i + 2];
    var a = imgData.data[i + 3];

    //[...] do what you want with these values
}

From this, how would I create a 2D array of RGB values of an entire canvas?


回答1:


var rgb = [];
for (var i=0;i<imgData.data.length;i+=4){

    // If you want to know the values of the pixel
    var r = imgData.data[i + 0];
    var g = imgData.data[i + 1];
    var b = imgData.data[i + 2];
    var a = imgData.data[i + 3];

    var x = Math.floor((i/4) % imageData.width);  
    var y = Math.floor((i/4) / imageData.width);
    rgb[x] ? (rgb[x][y] = [r,b,g,a]) : (rgb[x] = [[r,b,g,a]]);
}



回答2:


This may not be what you want, but if your concern is transferring the image data (not necessarily building an array on the client side), toDataURL() might be an even simpler way to transfer your image data...

The HTML5 canvas.toDataURL('image/png') method will produce a data URI for your image data - i.e. a really long, text-encoded version of the PNG. No need to grab the image data manually. Likewise, you could use a JPEG encoding if that's preferable.

If you send this string to the server, PHP can decoded back to binary form directly by passing it as the first argument to file_get_contents() (i.e. $binary = file_get_contents($dataURL)). You can then save this to disk or do whatever you want with the binary PNG data as you would with a file you had just loaded off disk.



来源:https://stackoverflow.com/questions/12291992/build-2d-array-of-canvas-rgb-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!