    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;
    019
    020import java.awt.RenderingHints;
    021import java.awt.Transparency;
    022import java.awt.color.ColorSpace;
    023import java.awt.color.ICC_ColorSpace;
    024import java.awt.color.ICC_Profile;
    025import java.awt.image.BufferedImage;
    026import java.awt.image.ColorConvertOp;
    027import java.awt.image.ColorModel;
    028import java.awt.image.ComponentColorModel;
    029import java.awt.image.DirectColorModel;
    030import java.awt.image.ImagingOpException;
    031import java.io.File;
    032import java.io.IOException;
    033
    034/**
    035 * A selection of tools for evaluating and manipulating color
    036 * spaces, color values, etc.
    037 * <p>The Javadoc provided in the original code gave the
    038 * following notation:<br><br>
    039 *
    040 * &nbsp;&nbsp;&nbsp; "This class is a mess and needs to be cleaned up."
    041 */
    042public class ColorTools {
    043
    044    public BufferedImage correctImage(final BufferedImage src, final File file)
    045            throws ImageReadException, IOException {
    046        final ICC_Profile icc = Imaging.getICCProfile(file);
    047        if (icc == null) {
    048            return src;
    049        }
    050
    051        final ICC_ColorSpace cs = new ICC_ColorSpace(icc);
    052
    053        return convertFromColorSpace(src, cs);
    054    }
    055
    056    public BufferedImage relabelColorSpace(final BufferedImage bi, final ICC_Profile profile)
    057            throws ImagingOpException {
    058        final ICC_ColorSpace cs = new ICC_ColorSpace(profile);
    059
    060        return relabelColorSpace(bi, cs);
    061    }
    062
    063    public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorSpace cs)
    064            throws ImagingOpException {
    065        // This does not do the conversion. It tries to relabel the
    066        // BufferedImage
    067        // with its actual (presumably correct) Colorspace.
    068        // use this when the image is mislabeled, presumably having been
    069        // wrongly assumed to be sRGB
    070
    071        final ColorModel cm = deriveColorModel(bi, cs);
    072
    073        return relabelColorSpace(bi, cm);
    074
    075    }
    076
    077    public BufferedImage relabelColorSpace(final BufferedImage bi, final ColorModel cm)
    078            throws ImagingOpException {
    079        // This does not do the conversion. It tries to relabel the
    080        // BufferedImage
    081        // with its actual (presumably correct) Colorspace.
    082        // use this when the image is mislabeled, presumably having been
    083        // wrongly assumed to be sRGB
    084
    085        return new BufferedImage(cm, bi.getRaster(), false, null);
    086    }
    087
    088    public ColorModel deriveColorModel(final BufferedImage bi, final ColorSpace cs)
    089            throws ImagingOpException {
    090        // boolean hasAlpha = (bi.getAlphaRaster() != null);
    091        return deriveColorModel(bi, cs, false);
    092    }
    093
    094    public ColorModel deriveColorModel(final BufferedImage bi, final ColorSpace cs,
    095            final boolean forceNoAlpha) throws ImagingOpException {
    096        return deriveColorModel(bi.getColorModel(), cs, forceNoAlpha);
    097    }
    098
    099    public ColorModel deriveColorModel(final ColorModel colorModel, final ColorSpace cs,
    100            final boolean forceNoAlpha) throws ImagingOpException {
    101
    102        if (colorModel instanceof ComponentColorModel) {
    103            final ComponentColorModel ccm = (ComponentColorModel) colorModel;
    104            // ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    105            if (forceNoAlpha) {
    106                return new ComponentColorModel(cs, false, false,
    107                        Transparency.OPAQUE, ccm.getTransferType());
    108            }
    109            return new ComponentColorModel(cs, ccm.hasAlpha(),
    110                    ccm.isAlphaPremultiplied(), ccm.getTransparency(),
    111                    ccm.getTransferType());
    112        } else if (colorModel instanceof DirectColorModel) {
    113            final DirectColorModel dcm = (DirectColorModel) colorModel;
    114
    115            final int oldMask = dcm.getRedMask() | dcm.getGreenMask()
    116                    | dcm.getBlueMask() | dcm.getAlphaMask();
    117
    118            final int oldBits = countBitsInMask(oldMask);
    119
    120            return new DirectColorModel(cs, oldBits, dcm.getRedMask(),
    121                    dcm.getGreenMask(), dcm.getBlueMask(), dcm.getAlphaMask(),
    122                    dcm.isAlphaPremultiplied(), dcm.getTransferType());
    123        }
    124        // else if (old_cm instanceof PackedColorModel)
    125        // {
    126        // PackedColorModel pcm = (PackedColorModel) old_cm;
    127        //
    128        // // int old_mask = dcm.getRedMask() | dcm.getGreenMask()
    129        // // | dcm.getBlueMask() | dcm.getAlphaMask();
    130        //
    131        // int old_masks[] = pcm.getMasks();
    132        // // System.out.println("old_mask: " + old_mask);
    133        // int old_bits = countBitsInMask(old_masks);
    134        // // System.out.println("old_bits: " + old_bits);
    135        //
    136        // // PackedColorModel(ColorSpace space, int bits, int rmask, int gmask,
    137        // int bmask, int amask, boolean isAlphaPremultiplied, int trans, int
    138        // transferType)
    139        // cm = new PackedColorModel(cs, old_bits, pcm.getMasks(),
    140        //
    141        // pcm.isAlphaPremultiplied(), pcm.getTransparency(), pcm
    142        // .getTransferType());
    143        // }
    144
    145        throw new ImagingOpException("Could not clone unknown ColorModel Type.");
    146    }
    147
    148    private int countBitsInMask(int i) {
    149        int count = 0;
    150        while (i != 0) {
    151            count += (i & 1);
    152            // uses the unsigned version of java's right shift operator,
    153            // so that left hand bits are zeroed.
    154            i >>>= 1;
    155        }
    156        return count;
    157    }
    158
    159    public BufferedImage convertToColorSpace(final BufferedImage bi, final ColorSpace to) {
    160        final ColorSpace from = bi.getColorModel().getColorSpace();
    161
    162        final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
    163                RenderingHints.VALUE_RENDER_QUALITY);
    164        hints.put(RenderingHints.KEY_COLOR_RENDERING,
    165                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    166        hints.put(RenderingHints.KEY_DITHERING,
    167                RenderingHints.VALUE_DITHER_ENABLE);
    168
    169        final ColorConvertOp op = new ColorConvertOp(from, to, hints);
    170
    171        BufferedImage result = op.filter(bi, null);
    172
    173        result = relabelColorSpace(result, to);
    174
    175        return result;
    176    }
    177
    178    public BufferedImage convertTosRGB(final BufferedImage bi) {
    179        final ColorModel srgbCM = ColorModel.getRGBdefault();
    180        return convertToColorSpace(bi, srgbCM.getColorSpace());
    181    }
    182
    183    protected BufferedImage convertFromColorSpace(final BufferedImage bi, final ColorSpace from) {
    184        final ColorModel srgbCM = ColorModel.getRGBdefault();
    185        return convertBetweenColorSpaces(bi, from, srgbCM.getColorSpace());
    186    }
    187
    188    public BufferedImage convertBetweenICCProfiles(final BufferedImage bi, final ICC_Profile from, final ICC_Profile to) {
    189        final ICC_ColorSpace csFrom = new ICC_ColorSpace(from);
    190        final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
    191
    192        return convertBetweenColorSpaces(bi, csFrom, csTo);
    193    }
    194
    195    public BufferedImage convertToICCProfile(final BufferedImage bi, final ICC_Profile to) {
    196        final ICC_ColorSpace csTo = new ICC_ColorSpace(to);
    197        return convertToColorSpace(bi, csTo);
    198    }
    199
    200    public BufferedImage convertBetweenColorSpacesX2(BufferedImage bi,
    201            final ColorSpace from, final ColorSpace to) {
    202        final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
    203                RenderingHints.VALUE_RENDER_QUALITY);
    204        hints.put(RenderingHints.KEY_COLOR_RENDERING,
    205                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    206        hints.put(RenderingHints.KEY_DITHERING,
    207                RenderingHints.VALUE_DITHER_ENABLE);
    208
    209        // bi = relabelColorSpace(bi, cs);
    210        // dumpColorSpace("\tcs_sRGB", cs_sRGB);
    211        // dumpColorSpace("\tColorModel.getRGBdefaultc",
    212        // ColorModel.getRGBdefault().getColorSpace());
    213
    214        bi = relabelColorSpace(bi, from);
    215        final ColorConvertOp op = new ColorConvertOp(from, to, hints);
    216        bi = op.filter(bi, null);
    217
    218        bi = relabelColorSpace(bi, from);
    219
    220        bi = op.filter(bi, null);
    221
    222        bi = relabelColorSpace(bi, to);
    223
    224        return bi;
    225
    226    }
    227
    228    public BufferedImage convertBetweenColorSpaces(BufferedImage bi,
    229            final ColorSpace from, final ColorSpace to) {
    230        final RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
    231                RenderingHints.VALUE_RENDER_QUALITY);
    232        hints.put(RenderingHints.KEY_COLOR_RENDERING,
    233                RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    234        hints.put(RenderingHints.KEY_DITHERING,
    235                RenderingHints.VALUE_DITHER_ENABLE);
    236
    237        final ColorConvertOp op = new ColorConvertOp(from, to, hints);
    238
    239        bi = relabelColorSpace(bi, from);
    240
    241        BufferedImage result = op.filter(bi, null);
    242
    243        result = relabelColorSpace(result, to);
    244
    245        return result;
    246    }
    247
    248}