ColorUtil.java

package org.genesys.util;

import com.jhlabs.image.MapColorsFilter;
import org.apache.commons.lang3.StringUtils;
import org.genesys.server.service.MappingService;
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 color, 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);
            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 {}", color);
            return imageBytes;
        } catch (final IOException e) {
            LOG.warn(e.getMessage());
            return imageBytes;
        }
    }
}