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 posterize an image.
024 */
025public class PosterizeFilter extends PointFilter {
026
027        private int numLevels;
028        private int[] levels;
029    private boolean initialized = false;
030
031        public PosterizeFilter() {
032                setNumLevels(6);
033        }
034        
035        /**
036     * Set the number of levels in the output image.
037     * @param numLevels the number of levels
038     * @see #getNumLevels
039     */
040    public void setNumLevels(int numLevels) {
041                this.numLevels = numLevels;
042                initialized = false;
043        }
044
045        /**
046     * Get the number of levels in the output image.
047     * @return the number of levels
048     * @see #setNumLevels
049     */
050        public int getNumLevels() {
051                return numLevels;
052        }
053
054        /**
055     * Initialize the filter.
056     */
057    protected void initialize() {
058                levels = new int[256];
059                if (numLevels != 1)
060                        for (int i = 0; i < 256; i++)
061                                levels[i] = 255 * (numLevels*i / 256) / (numLevels-1);
062        }
063        
064        public int filterRGB(int x, int y, int rgb) {
065                if (!initialized) {
066                        initialized = true;
067                        initialize();
068                }
069                int a = rgb & 0xff000000;
070                int r = (rgb >> 16) & 0xff;
071                int g = (rgb >> 8) & 0xff;
072                int b = rgb & 0xff;
073                r = levels[r];
074                g = levels[g];
075                b = levels[b];
076                return a | (r << 16) | (g << 8) | b;
077        }
078
079        public String toString() {
080                return "Colors/Posterize...";
081        }
082
083}
084