We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am making examples for reference of p5.image to be put in inline documentation (thereby for online reference). I have placed a PR for 3 examples that I was able to make successfully but I am not able to make it work for loadPixel() method of p5Image class. p5js.org/reference/#p5.Image/loadPixels
It is all about porting examples from processing. So I was porting from https://processing.org/reference/PImage_loadPixels_.html
So my code
var myImage;
var halfImage;
function preload(){
myImage = loadImage("assets/rockies.jpg");
}
function setup(){
myImage.loadPixels();
halfImage = width*height/2;
for(var i=0; i<halfImage; i++){
myImage.pixels[i+halfImage] = myImage.pixels[i];
}
myImage.updatePixels();
}
function draw(){
image(myImage, 0, 0);
}
Is not producing expected result. Then I looked at the loadPixel() of p5 class.p5js.org/reference/#p5/loadPixels. I guess this too is not producing desired result. Need someones guidance here. About what is the error in my code for loadPixels() for p5.image above.
PS - To run the code quickly - 1. Open http://p5js.org/reference/#/p5.Image/set 2. Click "edit" in example, delete existing code and paste this. 3. rockies.jpg is present in the assets of p5js-website and is accessible here.
Sorry for big question I tried putting everything I have done for clarity.
Answers
Java Mode's
color
datatype is a 32-bit (4 bytes) value, which contains the following 4 components:ALPHA, RED, GREEN & BLUE -> https://Processing.org/reference/color_datatype.html
Therefore, each index in Processing's
pixels[]
represents exactly 1 pixelcolor
value:https://Processing.org/reference/pixels.html
Unfortunately in p5.js, it's not that simple easy peachy! :-SS
Besides the order is now RGBa instead of aRGB like in Processing, each of those 4 components occupy its own index in
pixels[]
. That is, 1 full pixelcolor
is stored as 4 indices! @-)Thus a p5.js'
pixels[]
is at least 4x the length of the corresponding Processing's. :(That's why the
width*height/2
expression fails in p5.js version. We still need to multiply that by 4.Actually it'd be better if you had just based it on
pixels[]
's length instead. And divided it by 2:pixels.length / 2
orpixels.length >> 1
*-:)Another gr8 option is replacing the whole
for ( ; ; )
loop w/ arrayCopy(): :ar!http://p5js.org/reference/#/p5/arrayCopy
However arrayCopy(), due to negligent oversight, doesn't work on
pixels[]
!!! :-OB/c
pixels[]
isn't a regular array but an Uint8ClampedArray: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArrayThe whole p5.js API only checks for regular arrays, although it depends on Uint8ClampedArray too! >:P
You are a rockstar. This helped me with fixing this and other examples too.