ColorUtil.java

package org.genesys.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 org.genesys.server.service.MappingService;

import lombok.extern.slf4j.Slf4j;

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

/**
 * Utility class for performing color-related operations on images.
 * <p>
 * This class provides static methods to manipulate image data, specifically for changing
 * colors within an image. It is not designed to be instantiated.
 */
@Slf4j
public abstract class ColorUtil {

	/**
	 * Changes all occurrences of a default {@link MappingService.DEFAULT_TILE_COLOR} color within a tile image to a new specified color.
	 *
	 * @param color      The target color as a hex string (e.g., "#RRGGBB" or "RRGGBB").
	 * @param imageBytes The byte array representing the source PNG image.
	 * @return A byte array of the modified image. Returns the original image byte array if the color is invalid, blank, or the same as the default color.
	 */
	public static byte[] changeColor(String color, final byte[] imageBytes) {
		if (StringUtils.isBlank(color)) {
			return imageBytes;
		}

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

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

		try {
			final Color newColor = Color.decode(color);
			if (newColor.equals(MappingService.DEFAULT_TILE_COLOR)) {
				return imageBytes;
			}

			final int originalColor = MappingService.DEFAULT_TILE_COLOR.getRGB();
			final int updatedColor = newColor.getRGB();

			final MapColorsFilter mcf = new MapColorsFilter(originalColor, updatedColor);
			try (final ByteArrayInputStream bios = new ByteArrayInputStream(imageBytes);
					final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
				final BufferedImage image = mcf.filter(ImageIO.read(bios), null);
				ImageIO.write(image, "PNG", baos);
				return baos.toByteArray();
			}
		} catch (final NumberFormatException e) {
			log.warn("Cannot get color for {}", color);
			return imageBytes;
		} catch (final IOException e) {
			log.warn(e.getMessage());
			return imageBytes;
		}
	}
}