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.png;
018
019import java.util.logging.Level;
020import java.util.logging.Logger;
021
022public class GammaCorrection {
023
024    private static final Logger LOGGER = Logger.getLogger(GammaCorrection.class.getName());
025
026    private final int[] lookupTable;
027
028    public GammaCorrection(final double srcGamma, final double dstGamma) {
029
030        if (LOGGER.isLoggable(Level.FINEST)) {
031            LOGGER.finest("srcGamma: " + srcGamma);
032            LOGGER.finest("dstGamma: " + dstGamma);
033        }
034
035        lookupTable = new int[256];
036        for (int i = 0; i < 256; i++) {
037            lookupTable[i] = correctSample(i, srcGamma, dstGamma);
038            if (LOGGER.isLoggable(Level.FINEST)) {
039                LOGGER.finest("lookupTable[" + i + "]: " + lookupTable[i]);
040            }
041        }
042    }
043
044    public int correctArgb(final int pixel) {
045        final int alpha = 0xff000000 & pixel;
046        int red = pixel >> 16 & 0xff;
047        int green = pixel >> 8 & 0xff;
048        int blue = pixel >> 0 & 0xff;
049
050        red = correctSample(red);
051        green = correctSample(green);
052        blue = correctSample(blue);
053
054        return alpha | (0xff & red) << 16 | (0xff & green) << 8 | (0xff & blue) << 0;
055    }
056
057    public int correctSample(final int sample) {
058        return lookupTable[sample];
059    }
060
061    private int correctSample(final int sample, final double srcGamma, final double dstGamma) {
062        // if (kUseAdobeGammaMethod && val <= 32)
063        // {
064        // double slope = Math.round(255.0d * Math.pow((32.0 / 255.0d),
065        // src_gamma / dst_gamma)) / 32.d;
066        // return (int) (sample * slope);
067        // }
068
069        return (int) Math.round(255.0d * Math.pow(sample / 255.0d, srcGamma / dstGamma));
070    }
071
072}