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.*;
021
022/**
023 * A filter to change the saturation of an image. This works by calculating a grayscale version of the image
024 * and then extrapolating away from it.
025 */
026public class SaturationFilter extends PointFilter {
027        
028        public float amount = 1;
029        
030    /**
031     * Construct a SaturationFilter.
032     */
033        public SaturationFilter() {
034        }
035
036    /**
037     * Construct a SaturationFilter.
038     * The amount of saturation change.
039     */
040        public SaturationFilter( float amount ) {
041                this.amount = amount;
042                canFilterIndexColorModel = true;
043        }
044
045    /**
046     * Set the amount of saturation change. 1 leaves the image unchanged, values between 0 and 1 desaturate, 0 completely
047     * desaturates it and values above 1 increase the saturation.
048     * @param amount the amount
049     */
050        public void setAmount( float amount ) {
051                this.amount = amount;
052        }
053        
054    /**
055     * Set the amount of saturation change.
056     * @return the amount
057     */
058        public float getAmount() {
059                return amount;
060        }
061        
062        public int filterRGB(int x, int y, int rgb) {
063                if ( amount != 1 ) {
064            int a = rgb & 0xff000000;
065            int r = (rgb >> 16) & 0xff;
066            int g = (rgb >> 8) & 0xff;
067            int b = rgb & 0xff;
068            int v = ( r + g + b )/3; // or a better brightness calculation if you prefer
069            r = PixelUtils.clamp( (int)(v + amount * (r-v)) );
070            g = PixelUtils.clamp( (int)(v + amount * (g-v)) );
071            b = PixelUtils.clamp( (int)(v + amount * (b-v)) );
072            return a | (r << 16) | (g << 8) | b;
073        }
074        return rgb;
075        }
076
077        public String toString() {
078                return "Colors/Saturation...";
079        }
080}
081