Merging ofImages

Hi,

When I’ve got

  
ofImage a;  
a.loadImage("a.png");  
  
ofImage b;  
b.loadImage("b.png");  
  

Is there somewhich which combines/merges “b” into “a”?
like:

  
a.merge(b.getPixels()) ?  

Grtz!

Can you explain what the result of merging two images would look like? as in:

b overwrites a?
b is averaged with a? (50% 50%)?

to overwtire a with b:

  
  
a.setFromPixels(b.getPixels(),b.width,b.height,b.type);  
  

to average the colors from b into a: (assuming they are the same dimensions)

  
  
  
int totalPixels = a.width * a.height * a.bpp;  
unsigned char * aPixels = a.getPixels();  
unsigned char * bPixels = b.getPixels();  
  
for(int i=0; i<totalPixels; i++) {  
   aPixels[i] = (aPixels[i] +bPixels[i])/2;  
}  
  
  

Wow…
That is exactly what I tried yesterday?
Thank you!

Hi Tim,

Oh sorry for being unclear. Lets say I’ve two images A(400x400) and B(400x400). B is transparent and has a circle in the center with a radius of 100. Then I want to merge them
in such a way I get the same affect like drawing the two images over each other:

a.draw(0,0)
b.draw(0,0).

I could just “add” all pixels values in a for loop, but I wasnt sure if this is the way to go.

Roxlu

hi Rqxlu,

you need to multiply each pixel value by its alpha value, and then i think add the alphas together:

  
  
// a and b are both RGBA images  
int totalPixels = a.width * a.height;  
unsigned char * aPixels = a.getPixels();  
unsigned char * bPixels = b.getPixels();  
  
for(int i=0; i<totalPixels; i++) {  
   int base = totalPixels*4;  
   // deal with r,g,b  
   float bAlpha = float(bPixels[base+3])/256.0f;  
   for ( j=0; j<3; j++ )  
   {  
      // merge b into a based on b's alpha  
      aPixels[base+j] = (aPixels[base+j]*(1.0f-bAlpha) + bPixels[base+j]*bAlpha));  
   }  
   // full alpha (no transparency)  
   aPixels[base+3] = 255;  
}  
  

Maybe this can help people with the same problem as me. I had a RGB jpg image that I wanted to overlay with a RGBA png image and create new RGB jpg out of it. I based this on the answer by damian and edited it like this:

int totalBytes = photoPixels.getWidth() * photoPixels.getHeight() * photoPixels.getBytesPerPixel();
unsigned char * aBytes = photoPixels.getPixels();
unsigned char * bBytes = overlayPixels.getPixels();

int alphaOffset = 0;
float alpha = 0;
int currentColor = -1; //0 = r, 1 = g, 2 = b
for(int i=0; i < totalBytes; i++) {
	currentColor ++;
	if(currentColor == 3){
		currentColor = 0;
		alphaOffset ++;
	}
	alpha = bBytes[i+alphaOffset+(3-currentColor)] / 255.0f;
	aBytes[i] = (aBytes[i]*(1.0f-alpha) + bBytes[i+alphaOffset]*alpha);
}
1 Like

Hello,
i tried to implement the example code above, but it crashes…
so it would be great if there is an example how to use the code above…