ColorUtil.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.util;

import com.jhlabs.image.MapColorsFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ColorUtil {

    private final static Logger LOG = LoggerFactory.getLogger(ColorUtil.class);

    public static byte[] changeColor(String originalColor, String targetColor, byte[] imageBytes) {
        if (StringUtils.isBlank(targetColor)) {
            return imageBytes;
        }

        if (!targetColor.startsWith("#"))
            targetColor = "#" + targetColor;

        if (LOG.isDebugEnabled())
            LOG.debug("Changing color to {}", targetColor);

        try {
            final int sourceColor = Color.decode(originalColor).getRGB();
            final Color newColor = Color.decode(targetColor);
            final int updatedColor = newColor.getRGB();
            if (sourceColor == newColor.getRGB()) {
                return imageBytes;
            }

            final MapColorsFilter mcf = new MapColorsFilter(sourceColor, updatedColor);
            final ByteArrayInputStream bios = new ByteArrayInputStream(imageBytes);
            final BufferedImage image = mcf.filter(ImageIO.read(bios), null);

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", baos);
            return baos.toByteArray();

        } catch (final NumberFormatException e) {
            LOG.warn("Cannot get color for {}", targetColor);
            return imageBytes;
        } catch (final IOException e) {
            LOG.warn(e.getMessage());
            return imageBytes;
        }
    }
}