alpha blending by hand

Hrm, I can’t seem to get this code working to blend colors together. If anyone has done this, show me some quick code to blend these values, no lookup tables or any bullshit, just the raw operations.

red source pixel = 255
red destination pixel = 0
source pixel alpha value of 127

I think I want what AlphaComposite specifies as SRC_OVER. Destination is an opaque pixel and were blending a source pixel into that with it’s alpha value. I’ve tried alot of different things and I’ve gotten alot of really strange results. bleh, nothing but problems today.

Something like this if you have an array of source pixels and dest pixels:

        int alpha;
        float aS, aD;
        float sr, sg, sb, dr, dg, db;
        
        for (int i = 0; i != src.length; i++) {
              alpha = src[i] >> 24 & 0xFF;
              aS = (float) alpha / 255.0F;
              aD = 1 - aS;
              
              if (alpha == 255) {
                    dest[i] = src[i];
              } else if (alpha > 0) {
                    sr = src[i] >> 16 & 0xFF;
                    sg = src[i] >> 8 & 0xFF;
                    sb = src[i] >> 0 & 0xFF;
                    dr = dest[i] >> 16 & 0xFF;
                    dg = dest[i] >> 8 & 0xFF;
                    db = dest[i] >> 0 & 0xFF;
                    dest[i] = (255 << 24) | (byte) ((sr * aS) + (dr * aD)) << 16 |
                                (byte) ((sg * aS) + (dg * aD)) << 8 |
                                (byte) ((sb * aS) + (db * aD)) << 0;
              }
        }

I would just like say, NI. Thank you.

Edit: Oh, can anyone confirm that this is accurate and indeed what I was trying to accomplish?

Four years ago I wrote the following code:


      public static void blend(int[] src, int[] dst)
      {
            int length = dst.length;
            for (int i = 0; i < length; ++i)
            {
                  int srcval = src[i];
                  int dstval = dst[i];
                  
                  int alpha = (srcval >>> 24) + 1; // make alpha in [1, 256] range...
                  
                  int srb = srcval & 0x00ff00ff;
                  int drb = dstval & 0x00ff00ff;
                  int rb  = ((((srb - drb) * alpha) >>> 8) + drb) & 0x00ff00ff;
            
                  int sag = (srcval & 0xff00ff00) >>> 8;
                  int dag = (dstval & 0xff00ff00) >>> 8;
                  int ag  = (((((sag - dag) * alpha) >>> 8) + dag) << 8) & 0xff00ff00;
            
                  dst[i] = ag | rb;
            }
      }

This piece of code is from my own rasterizer (capable to draw antialiased lines with different colors at ends, blending and so on) written in Java 1.0. As far as I remember I’d spent several hours to optimize this function and algorithm so the final performance of it is quite good (for pure Java). 8)

Hope this helps…