简体   繁体   中英

Build 2D Array of Canvas RGB values

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?

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]]);
}

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 - ie 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() (ie $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM