Problem with example in reference

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.

It is all about porting examples from processing. So I was porting from

So my code

            var myImage;
            var halfImage;

            function preload(){
              myImage = loadImage("assets/rockies.jpg");

            function setup(){
              halfImage = width*height/2;
              for(var i=0; i<halfImage; i++){
                myImage.pixels[i+halfImage] = myImage.pixels[i];

            function draw(){
              image(myImage, 0, 0);

Is not producing expected result. Then I looked at the loadPixel() of p5 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 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.


  • edited January 2016 Answer ✓

    Java Mode's color datatype is a 32-bit (4 bytes) value, which contains the following 4 components:

    Therefore, each index in Processing's pixels[] represents exactly 1 pixel color value:

    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 pixel color 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 or pixels.length >> 1 *-:)

    Another gr8 option is replacing the whole for ( ; ; ) loop w/ arrayCopy(): :ar!

    const halfImage = myImage.pixels.length >> 1;
    arrayCopy(myImage.pixels, 0, myImage.pixels, halfImage, halfImage);

    However arrayCopy(), due to negligent oversight, doesn't work on pixels[]!!! :-O
    B/c pixels[] isn't a regular array but an Uint8ClampedArray:

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

Sign In or Register to comment.