How to change image color without iterating each pixel individually ?

edited November 2013 in How To...

Hi, I know that we can change pixels color of any jpg or png just by iterating each pixel one by one individually like this

    PImage img = loadImage("rockies.jpg");
    image(img, 0, 0);
    img.loadPixels();
    for (int i = 0; i < img.width*img.height; i++) {
      img.pixels[i] = color(255,0,0);
    }
    img.updatePixels();

but can we do the same without iterating each pixels/without any loop just by setting all pixel same color in a one go something like this imagecolor = set(0,255,0); . Is there any method exits like this ? The purpose of this is to make fast.

So is there any fast method to do this, setting all pixels to same color ?

Answers

  • edited November 2013 Answer ✓

    You can use Arrays.fill() method. But it's necessary to import java.util.Arrays ~O)
    And if you use PGraphics you can use background() + endDraw() too. :-c

    Also, for performance reasons, we don't need to invoke loadPixels() when we aren't interested at reading pixels[] content! :-B
    And in the same vein, updatePixels() isn't needed when we don't modify pixels[]! <):)

    1 more tip: Avoid using color() when you can! :-\"

  • GoToLoop Thank a lot! =D> Can you elaborate how to use Array.fill() with a jpg image

  • edited November 2013 Answer ✓

    It's Arrays, not Array. Don't mix them up! They're diff. classes! :-t

    For Arrays.fill(), you're gonna need an array plus the filling value:
    http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#fill(int[], int)

    For example:

    Arrays.fill(img.pixels, #FF0000);
    img.updatePixels();
    
  • thanks ^:)^ ^:)^ ^:)^ :D :D

Sign In or Register to comment.