Png image question

How to read the position of the opaque area on the ‘png’ image?
the alpha() function?

void mkey() {
for (int i = 0; i<img.width; i++) {
for (int j = 0; j<img.height; j++) {
int index = i+j*img.width;
color col = img.pixels[index];
float alp = alpha(col);
//float alp = brightness(col);
if (alp>1) {
??? //
}
}
}
img.updatePixels();
}

It depends a bit on the renderer you are using. But it makes sense to use get(x, y) instead of the pixels array. Working with the alpha() function is the right way to go. Here is an example on how to recolor the alpha values of an image with green color.

Be aware that the alpha value range is between 0-255! So here I only replace everything that is lower then 200. And this kind of pixel manipulation is really slow and should not be used for 60 fps applications.

PImage img;

void setup()
{
  size(500, 500);
  img = loadImage("https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png");
  noLoop();
}

void draw()
{
  for (int y = 0; y < img.height; y++)
  {
    for (int x = 0; x < img.width; x++)
    {
      if (alpha(img.get(x, y)) < 200)
        img.set(x, y, color(0, 255, 0, 255));
    }
  }

  image(img, 0, 0);
}
1 Like

Useing pixels[] is faster than get(). However you will have to call loadPixels() before looking at them and updatePixels() after you made a change.

2 Likes