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 class PhotometricInterpreterPalette extends PhotometricInterpreter {
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     *
046     * @throws ImagingFormatException     if an index into the {@code colorMap} is out of bounds.
047     * @throws AllocationRequestException Thrown when an allocation request exceeds the {@link Allocator} limit.
048     */
049    public PhotometricInterpreterPalette(final int samplesPerPixel, final int[] bitsPerSample, final int predictor, final int width, final int height,
050            final int[] colorMap) {
051        super(samplesPerPixel, bitsPerSample, predictor, width, height);
052
053        final int bitsPerPixel = getBitsPerSample(0);
054        final int colorMapScale = 1 << bitsPerPixel;
055        int colorMapScaleX2;
056        try {
057            colorMapScaleX2 = Math.multiplyExact(2, colorMapScale);
058        } catch (final ArithmeticException e) {
059            throw new ImagingFormatException("bitsPerPixel is too large or colorMap is too small", e);
060        }
061        // Validate colorMap[i], colorMap[i + colorMapScale], and colorMap[i + colorMapScaleX2] where max(i) is
062        // colorMapScale - 1.
063        int maxI;
064        try {
065            maxI = Math.addExact(colorMapScaleX2, colorMapScale - 1);
066        } catch (final ArithmeticException e) {
067            throw new ImagingFormatException("bitsPerPixel is too large or colorMap is too small", e);
068        }
069        if (maxI >= colorMap.length) {
070            throw new ImagingFormatException("bitsPerPixel %,d (maxI = %,d) is too large or colorMap is too small %,d", bitsPerPixel, maxI, colorMap.length);
071        }
072        indexColorMap = Allocator.intArray(colorMapScale);
073        Arrays.setAll(indexColorMap, i -> {
074            final int red = colorMap[i] >> 8 & 0xff;
075            final int green = colorMap[i + colorMapScale] >> 8 & 0xff;
076            final int blue = colorMap[i + colorMapScaleX2] >> 8 & 0xff;
077            return 0xff000000 | red << 16 | green << 8 | blue;
078        });
079
080        // Fix for IMAGING-247 5/17/2020
081        // This interpreter is used with TIFF_COMPRESSION_PACKBITS (32773).
082        // which unpacks to 8 bits per sample. But if the bits-per-pixel
083        // is less than 8 bits, some authoring tools do not zero-out the
084        // unused bits. This results in cases where the decoded by index
085        // exceeds the size of the palette. So we set up a mask to protect
086        // the code from an array bounds exception.
087        int temp = 0;
088        for (int i = 0; i < bitsPerPixel; i++) {
089            temp = temp << 1 | 1;
090        }
091        bitsPerPixelMask = temp;
092
093    }
094
095    @Override
096    public void interpretPixel(final ImageBuilder imageBuilder, final int[] samples, final int x, final int y) throws ImagingException, IOException {
097        imageBuilder.setRgb(x, y, indexColorMap[samples[0] & bitsPerPixelMask]);
098    }
099}