001/*
002Copyright 2006 Jerry Huxtable
003
004Licensed under the Apache License, Version 2.0 (the "License");
005you may not use this file except in compliance with the License.
006You may obtain a copy of the License at
007
008   http://www.apache.org/licenses/LICENSE-2.0
009
010Unless required by applicable law or agreed to in writing, software
011distributed under the License is distributed on an "AS IS" BASIS,
012WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013See the License for the specific language governing permissions and
014limitations under the License.
015*/
016
017package com.jhlabs.composite;
018
019import java.awt.*;
020import java.awt.image.*;
021
022public final class ColorComposite extends RGBComposite {
023
024        public ColorComposite( float alpha ) {
025        super( alpha );
026        }
027
028        public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints ) {
029                return new Context( extraAlpha, srcColorModel, dstColorModel );
030        }
031
032    static class Context extends RGBCompositeContext {
033                private float[] sHSB = new float[3];
034        private float[] dHSB = new float[3];
035
036        public Context( float alpha, ColorModel srcColorModel, ColorModel dstColorModel ) {
037            super( alpha, srcColorModel, dstColorModel );
038        }
039
040        public void composeRGB( int[] src, int[] dst, float alpha ) {
041            int w = src.length;
042
043            for ( int i = 0; i < w; i += 4 ) {
044                int sr = src[i];
045                int dir = dst[i];
046                int sg = src[i+1];
047                int dig = dst[i+1];
048                int sb = src[i+2];
049                int dib = dst[i+2];
050                int sa = src[i+3];
051                int dia = dst[i+3];
052                int dor, dog, dob;
053
054                Color.RGBtoHSB( sr, sg, sb, sHSB );
055                Color.RGBtoHSB( dir, dig, dib, dHSB );
056
057                dHSB[0] = sHSB[0];
058                dHSB[1] = sHSB[1];
059
060                int doRGB = Color.HSBtoRGB( dHSB[0], dHSB[1], dHSB[2] );
061                dor = (doRGB & 0xff0000) >> 16;
062                dog = (doRGB & 0xff00) >> 8;
063                dob = (doRGB & 0xff);
064
065                float a = alpha*sa/255f;
066                float ac = 1-a;
067
068                dst[i] = (int)(a*dor + ac*dir);
069                dst[i+1] = (int)(a*dog + ac*dig);
070                dst[i+2] = (int)(a*dob + ac*dib);
071                dst[i+3] = (int)(sa*alpha + dia*ac);
072            }
073        }
074    }
075
076}