Newer
Older
ChallengeSystem / src / main / java / de / fanta / challenges / utils / ChatSkullAPI / Message.java
@fantahund fantahund on 8 Sep 2020 2 KB Add ChatSkull API
package de.fanta.challenges.utils.ChatSkullAPI;

import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import net.md_5.bungee.api.ChatColor;
import org.bukkit.entity.Player;

public class Message {
  
  private String[] lines;
  
  public Message(BufferedImage image, int height, char imgChar) {
    ChatColor[][] chatColors = toChatColorArray(image, height);
    this.lines = toImgMessage(chatColors, imgChar);
  }
  
  public Message appendText(String[] text) {
    for (int y = 0; y < this.lines.length; y++) {
      if (text.length > y) {
        int tmp16_15 = y;
        String[] tmp16_12 = this.lines;
        tmp16_12[tmp16_15] = tmp16_12[tmp16_15] + " " + text[y];
      } 
    } 
    return this;
  }

  private ChatColor[][] toChatColorArray(BufferedImage image, int height) {
    double ratio = (image.getHeight() / image.getWidth());
    BufferedImage resized = resizeImage(image, (int)(height / ratio), height);
    ChatColor[][] chatImg = new ChatColor[resized.getWidth()][resized.getHeight()];
    for (int x = 0; x < resized.getWidth(); x++) {
      for (int y = 0; y < resized.getHeight(); y++) {
        int rgb = resized.getRGB(x, y);
        String hex = "#" + Integer.toHexString(rgb).substring(2);
        ChatColor closest = getClosestChatColor(ChatColor.of(hex));
        chatImg[x][y] = closest;
      } 
    } 
    return chatImg;
  }
  
  private String[] toImgMessage(ChatColor[][] colors, char imgchar) {
    String[] lines = new String[(colors[0]).length];
    for (int y = 0; y < (colors[0]).length; y++) {
      StringBuilder line = new StringBuilder();
      for (ChatColor[] chatColors : colors) {
        ChatColor color = chatColors[y];
        line.append((color != null) ? (chatColors[y].toString() + imgchar) : Character.valueOf(' '));
      } 
      lines[y] = line.toString() + ChatColor.RESET;
    } 
    return lines;
  }
  
  private BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
    AffineTransform af = new AffineTransform();
    af.scale((width / originalImage.getWidth()), (height / originalImage.getHeight()));
    AffineTransformOp operation = new AffineTransformOp(af, 1);
    return operation.filter(originalImage, null);
  }
  
  public String[] getLines() {
    return this.lines;
  }
  
  public void sendToPlayer(Player player) {
    byte b;
    int i;
    String[] arrayOfString;
    for (i = (arrayOfString = this.lines).length, b = 0; b < i; ) {
      String line = arrayOfString[b];
      player.sendMessage(line);
      b++;
    } 
  }

  private ChatColor getClosestChatColor(ChatColor color) {
    return color;
  }
}