001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019
020package lucee.runtime.img.composite;
021
022import java.awt.CompositeContext;
023import java.awt.RenderingHints;
024import java.awt.image.ColorModel;
025
026public final class AverageComposite extends RGBComposite {
027
028        public AverageComposite( float alpha ) {
029        super( alpha );
030        }
031
032        public CompositeContext createContext( ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints ) {
033                return new Context( extraAlpha, srcColorModel, dstColorModel );
034        }
035
036    static class Context extends RGBCompositeContext {
037        public Context( float alpha, ColorModel srcColorModel, ColorModel dstColorModel ) {
038            super( alpha, srcColorModel, dstColorModel );
039        }
040
041        public void composeRGB( int[] src, int[] dst, float alpha ) {
042            int w = src.length;
043
044            for ( int i = 0; i < w; i += 4 ) {
045                int sr = src[i];
046                int dir = dst[i];
047                int sg = src[i+1];
048                int dig = dst[i+1];
049                int sb = src[i+2];
050                int dib = dst[i+2];
051                int sa = src[i+3];
052                int dia = dst[i+3];
053                int dor, dog, dob;
054
055                dor = (dir + sr) / 2;
056                dog = (dig + sg) / 2;
057                dob = (dib + sb) / 2;
058
059                float a = alpha*sa/255f;
060                float ac = 1-a;
061
062                dst[i] = (int)(a*dor + ac*dir);
063                dst[i+1] = (int)(a*dog + ac*dig);
064                dst[i+2] = (int)(a*dob + ac*dib);
065                dst[i+3] = (int)(sa*alpha + dia*ac);
066            }
067        }
068    }
069
070}