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 */
017package org.apache.commons.imaging.formats.tiff.photometricinterpreters;
018
019import java.io.IOException;
020import java.util.Arrays;
021
022import org.apache.commons.imaging.ImagingException;
023import org.apache.commons.imaging.ImagingFormatException;
024import org.apache.commons.imaging.common.AllocationRequestException;
025import org.apache.commons.imaging.common.Allocator;
026import org.apache.commons.imaging.common.ImageBuilder;
027
028public final class PhotometricInterpreterPalette extends AbstractPhotometricInterpreter {
029
030    /**
031     * The color map of integer ARGB values tied to the pixel index of the palette.
032     */
033    private final int[] indexColorMap;
034    private final int bitsPerPixelMask;
035
036    /**
037     * Constructs a new instance.
038     *
039     * @param samplesPerPixel Samples per pixel.
040     * @param bitsPerSample   Bits per sample.
041     * @param predictor       TODO
042     * @param width           TODO
043     * @param height          TODO
044     * @param colorMap        TODO
045     * @throws ImagingFormatException     if an index into the {@code colorMap} is out of bounds.
046     * @throws AllocationRequestException Thrown when an allocation request exceeds the {@link Allocator} limit.
047     */
048    public PhotometricInterpreterPalette(final int samplesPerPixel, final int[] bitsPerSample, final int predictor, final int width, final int height,
049            final int[] colorMap) {
050        super(samplesPerPixel, bitsPerSample, predictor, width, height);
051
052        final int bitsPerPixel = getBitsPerSample(0);
053        final int colorMapScale = 1 << bitsPerPixel;
054        final int colorMapScaleX2;
055        try {
056            colorMapScaleX2 = Math.multiplyExact(2, colorMapScale);
057        } catch (final ArithmeticException e) {
058            throw new ImagingFormatException("bitsPerPixel is too large or colorMap is too small", e);
059        }
060        // Validate colorMap[i], colorMap[i + colorMapScale], and colorMap[i + colorMapScaleX2] where max(i) is
061        // colorMapScale - 1.
062        final int maxI;
063        try {
064            maxI = Math.addExact(colorMapScaleX2, colorMapScale - 1);
065        } catch (final ArithmeticException e) {
066            throw new ImagingFormatException("bitsPerPixel is too large or colorMap is too small", e);
067        }
068        if (maxI >= colorMap.length) {
069            throw new ImagingFormatException("bitsPerPixel %,d (maxI = %,d) is too large or colorMap is too small %,d", bitsPerPixel, maxI, colorMap.length);
070        }
071        indexColorMap = Allocator.intArray(colorMapScale);
072        Arrays.setAll(indexColorMap, i -> {
073            final int red = colorMap[i] >> 8 & 0xff;
074            final int green = colorMap[i + colorMapScale] >> 8 & 0xff;
075            final int blue = colorMap[i + colorMapScaleX2] >> 8 & 0xff;
076            return 0xff000000 | red << 16 | green << 8 | blue;
077        });
078
079        // Fix for IMAGING-247 5/17/2020
080        // This interpreter is used with TIFF_COMPRESSION_PACKBITS (32773).
081        // which unpacks to 8 bits per sample. But if the bits-per-pixel
082        // is less than 8 bits, some authoring tools do not zero-out the
083        // unused bits. This results in cases where the decoded by index
084        // exceeds the size of the palette. So we set up a mask to protect
085        // the code from an array bounds exception.
086        int temp = 0;
087        for (int i = 0; i < bitsPerPixel; i++) {
088            temp = temp << 1 | 1;
089        }
090        bitsPerPixelMask = temp;
091
092    }
093
094    @Override
095    public void interpretPixel(final ImageBuilder imageBuilder, final int[] samples, final int x, final int y) throws ImagingException, IOException {
096        imageBuilder.setRgb(x, y, indexColorMap[samples[0] & bitsPerPixelMask]);
097    }
098}