001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.imaging.formats.png;
019
020import java.util.Arrays;
021
022public enum PngColorType {
023
024    // FIXME can this be merged with ImageInfo.ColorType?
025
026    GREYSCALE(0, true, false, 1, new int[] { 1, 2, 4, 8, 16 }), TRUE_COLOR(2, false, false, 3, new int[] { 8, 16 }),
027    INDEXED_COLOR(3, false, false, 1, new int[] { 1, 2, 4, 8 }), GREYSCALE_WITH_ALPHA(4, true, true, 2, new int[] { 8, 16 }),
028    TRUE_COLOR_WITH_ALPHA(6, false, true, 4, new int[] { 8, 16 });
029
030    static PngColorType getColorType(final boolean alpha, final boolean grayscale) {
031        if (grayscale) {
032            if (alpha) {
033                return GREYSCALE_WITH_ALPHA;
034            }
035            return GREYSCALE;
036        }
037        if (alpha) {
038            return TRUE_COLOR_WITH_ALPHA;
039        }
040        return TRUE_COLOR;
041    }
042
043    public static PngColorType getColorType(final int value) {
044        for (final PngColorType type : values()) {
045            if (type.value == value) {
046                return type;
047            }
048        }
049
050        return null;
051    }
052
053    private final int value;
054    private final boolean greyscale;
055    private final boolean alpha;
056
057    private final int samplesPerPixel;
058
059    private final int[] allowedBitDepths;
060
061    PngColorType(final int value, final boolean greyscale, final boolean alpha, final int samplesPerPixel, final int[] allowedBitDepths) {
062        this.value = value;
063        this.greyscale = greyscale;
064        this.alpha = alpha;
065        this.samplesPerPixel = samplesPerPixel;
066        this.allowedBitDepths = allowedBitDepths;
067    }
068
069    int getSamplesPerPixel() {
070        return samplesPerPixel;
071    }
072
073    int getValue() {
074        return value;
075    }
076
077    boolean hasAlpha() {
078        return alpha;
079    }
080
081    boolean isBitDepthAllowed(final int bitDepth) {
082        return Arrays.binarySearch(allowedBitDepths, bitDepth) >= 0;
083    }
084
085    boolean isGreyscale() {
086        return greyscale;
087    }
088}