ColorUtil.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.util;

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

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

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;
		}
	}
}