pixel array instead of copy()

edited March 2016 in Questions about Code

Hi people, How would you go about building something similar to the code below without using get(), set() and/or copy()? To be exact I'm looking for a way get similar effects (cutting slices of an image and applying them elsewhere in this particular example) by using pixel arrays and understand them better. I've been struggling with this so I'd appreciate some help from you guys.

Thanks in advance, oz

PImage source;
int x1, x2, y1, y2, w, h;

void setup() {
  size(800, 600);
  source = loadImage("parasutto.jpg");
}

void draw() {
  //imageMode(CENTER);
  //image(source, width/2, height / 2);

  source.loadPixels();

  // get location and dimensions for rectangular slices
  x1 = (int) random(source.width);
  y1 = 0;
  x2 = (int) (x1 + random(-5, 5));
  y2 = (int) random(-100, 20);
  w = (int) random(-10, 10);
  h = source.height;

  //copy the slices
  pushMatrix();
  translate(width / 4, height / 4);
  copy(source, x1, y1, w, h, x2, y2, w, h);
  popMatrix();

  updatePixels();
}
Tagged:

Answers

  • Copying a full width slice from one part of the image to another part using the pixel array is easy enough. The code below demonstrates how to do it, obviously I used my own image ;)

    If you wanted to copy rectangular areas that are not full width the code would be significantly more complex because the pixels to move would not be a contigious block.

    PImage source;
    
    void setup() {
      size(500, 324); // I have made this the same size as the image
      source = loadImage("london.jpg");
      frameRate(0.2); // Frame every 5 seconds
    }
    
    void draw() {
      background(255);
      int sliceHeight = (int) random(5, 20);
      int sliceYsource = (int) random(0, height - sliceHeight);
      int sliceYdest = (int) random(0, height - sliceHeight);
      copyHorizontalSlice(source, sliceYsource, sliceHeight, sliceYdest);
      image(source, 0, 0);
    }
    
    void copyHorizontalSlice(PImage img, int ys, int hs, int yd) {
      img.loadPixels();
      int pxlSource = ys * img.width;
      int nbrPxls =  hs * img.width;
      int pxlDest =  yd * img.width;
      arrayCopy(img.pixels, pxlSource, img.pixels, pxlDest, nbrPxls);
      img.updatePixels();
    }
    
Sign In or Register to comment.