PImage alpha color problems P2D

There is a problem amending the alpha channel in pixel arrays in P2D, under FX2D alpha can be adjusted like so

image

image

however the same code in P2D.

image

confirm, P2D this alpha mask not work ( win 10 / processing 3.5.3 )
JAVA2D and FX2D ok

testcode
//https://discourse.processing.org/t/pimage-alpha-color-problems-p2d/16648

String frogfile = "data/frog.jpeg";
PImage frog,img;
int w,h;

void setup() {
  size(500, 500);//P2D,FX2D);
  frog = loadImage(frogfile);
  w =frog.width;
  h =frog.height;
  println(w," * ",h);
}

void draw(){
  background(200,200,0);
  mouse_mask();
  fill(0,0,0);
  rect(0,0,w,h);
  image(img,0,0);
}

void mouse_mask() {
  img=frog.copy();
  img.loadPixels();
  for ( int i = 0; i < w*h ; i++ ) {
    color c = img.pixels[i];
    float d = constrain(dist(i%w,floor(i/w),mouseX,mouseY),0,100);
    int alpha = (int)map(d,0,100,255,1);
    img.pixels[i] = color (red(c),green(c),blue(c), alpha );
  }
  img.updatePixels();
}

Confirmed, above code writing to the alpha channel of an PImage doesn’t work here either. However, this workaround does give the desired result using P2D:

PImage frog;
PGraphics mask;

void setup() {
  size(330, 280, P2D);
  frog = loadImage("data/frog.jpg");
  mask = createGraphics(width, height);
}

void draw() {
  background(0);
  frog.mask(mouseMask(mask));
  image(frog, 0, 0);
}

PGraphics mouseMask(PGraphics pg) {
  
  pg.beginDraw();
  pg.loadPixels();
  for ( int i = 0; i < pg.pixels.length; i++ ) {
    float d = constrain(dist(i%pg.width, floor(i/pg.width), mouseX, mouseY), 0, 100);
    int alpha = (int) map(d, 0, 100, 255, 1);
    pg.pixels[i] = color(alpha);
  }
  pg.updatePixels();
  pg.endDraw();
  return pg;
}
4 Likes

Also, don’t need to redraw the radial gradient every frame:

PImage frog;
PGraphics mask, gradient;

void setup() {
  size(330, 280, P2D);
  
  frog = loadImage("data/frog.jpg");
  mask = createGraphics(frog.width, frog.height);
  gradient = createGradient(100);
  
}

void draw() {
  background(0);
  
  frog.mask(mouseMask(mask, gradient));
  image(frog, 0, 0);
}

PGraphics mouseMask(PGraphics pg, PGraphics mask) {
  
  pg.beginDraw();
  pg.background(0);
  pg.imageMode(CENTER);
  pg.image(mask, mouseX, mouseY);
  pg.endDraw();
  return pg;
}

PGraphics createGradient(int rad) {
  PGraphics pg = createGraphics(rad*2, rad*2);
  pg.beginDraw();
  pg.loadPixels();
  for ( int i = 0; i < pg.pixels.length; i++ ) {
    float d = constrain(dist(i%pg.width, floor(i/pg.width), pg.width/2, pg.height/2), 0, rad);
    int alpha = (int) map(d, 0, rad, 255, 0);
    pg.pixels[i] = color(alpha);
  }
  pg.updatePixels();
  pg.endDraw();
  return pg;
}