Blending image with a shape

I want to blend an image with a shape and get only the image portion under the shape. I try this way. But it didn’t work.

Here is the code I write in the setup();

image.load("img.jpg");

Here is the code I write in the draw();

image.draw(0, 0, 500, 500);
glEnable(GL_BLEND);
glBlendFunc(GL_ZERO, GL_SRC_ALPHA);
ofSetColor(255, 255, 255, 255);
ofDrawRectangle(100, 100, 100, 100);
glDisable(GL_BLEND);

Any idea to do it??

Hi,
You could use a shader, like the example /examples/shader/05_alphaMasking.
That example uses two images, but you could use an ofFbo for the alpha mask instead, like this:

in ofApp.h add
ofFbo f;
in ofApp.cpp setup() add

f.allocate(image.getWidth(), image.getHeight(), GL_RGBA);
f.begin();
  ofClear(0, 0, 0, 0);
  ofSetColor(0, 0, 0, 255);
  ofDrawRectangle(f.getWidth()*0.25, 0, f.getWidth()*0.5, f.getHeight());
f.end();

And then use draw() like this:

//--------------------------------------------------------------
void ofApp::draw(){
    
    // draw a white rectangle for background.
    ofDrawRectangle(0, 0, image.getWidth(), image.getHeight());
    
    f.begin();
        ofClear(0, 0, 0, 0);
        ofSetColor(0, 0, 0, 255);
        ofDrawRectangle(f.getWidth()*0.25, 0, f.getWidth()*0.5, f.getHeight());
    f.end();
    
    shader.begin();
    shader.setUniformTexture("imageMask", f.getTexture(), 1);

    image.draw(0, 0);
    
    shader.end();
}
1 Like

Hi,
In the same spirit you can use setAlphaMask() instead of a shader:
1- draw the shape into a ofFbo
2- set the mask for the image: image.getTexture().setAlphaMask( fbo.getTexture() )
3- draw the image
You’ve got a code example here, with a video instead of an image. You had to replace the ofVideoPlayer by a ofImage.

2 Likes

Thank you @Jildert

Thank you @lilive