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.image;
018
019import java.awt.*;
020import java.awt.image.*;
021import java.util.*;
022
023/**
024 * A filter which allows channels to be swapped. You provide a matrix with specifying the input channel for 
025 * each output channel.
026 */
027public class SwizzleFilter extends PointFilter {
028
029    private int[] matrix = {
030        1, 0, 0, 0, 0,
031        0, 1, 0, 0, 0,
032        0, 0, 1, 0, 0,
033        0, 0, 0, 1, 0
034    };
035    
036        public SwizzleFilter() {
037        }
038
039    /**
040     * Set the swizzle matrix.
041     * @param matrix the matrix
042     * @see #getMatrix
043     */
044        public void setMatrix( int[] matrix ) {
045                this.matrix = matrix;
046        }
047
048    /**
049     * Get the swizzle matrix.
050     * @return the matrix
051     * @see #setMatrix
052     */
053        public int[] getMatrix() {
054                return matrix;
055        }
056
057        public int filterRGB(int x, int y, int rgb) {
058                int a = (rgb >> 24) & 0xff;
059                int r = (rgb >> 16) & 0xff;
060                int g = (rgb >> 8) & 0xff;
061                int b = rgb & 0xff;
062
063        a = matrix[0]*a + matrix[1]*r + matrix[2]*g + matrix[3]*b + matrix[4]*255;
064        r = matrix[5]*a + matrix[6]*r + matrix[7]*g + matrix[8]*b + matrix[9]*255;
065        g = matrix[10]*a + matrix[11]*r + matrix[12]*g + matrix[13]*b + matrix[14]*255;
066        b = matrix[15]*a + matrix[16]*r + matrix[17]*g + matrix[18]*b + matrix[19]*255;
067
068        a = PixelUtils.clamp( a );
069        r = PixelUtils.clamp( r );
070        g = PixelUtils.clamp( g );
071        b = PixelUtils.clamp( b );
072
073        return (a << 24) | (r << 16) | (g << 8) | b;
074        }
075
076        public String toString() {
077                return "Channels/Swizzle...";
078        }
079        
080}
081