概要

JListを使用してGIF画像のカラーパレットと透過色を一覧表示します。

サンプルコード

class PaletteListModel extends AbstractListModel<IndexedColor> {
  private final transient IndexColorModel model;

  protected PaletteListModel(IndexColorModel model) {
    super();
    this.model = model;
  }

  @Override public int getSize() {
    return model.getMapSize();
  }

  @Override public IndexedColor getElementAt(int index) {
    boolean isTrans = index == model.getTransparentPixel();
    return new IndexedColor(index, new Color(model.getRGB(index)), isTrans);
  }
}
// ...
Image makeTestImage(
    DataBuffer dataBuffer, ColorModel colorModel, int w, int h, int transIdx) {
  // DataBufferByte dataBufferByte = null;
  // if (dataBuffer instanceof DataBufferByte) {
  //   dataBufferByte = (DataBufferByte) dataBuffer;
  // } else {
  //   System.out.println("No DataBufferByte");
  // }
  // byte data[] = dataBufferByte.getData();
  BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
  for (int y = 0; y < h; y++) {
    for (int x = 0; x < w; x++) {
      int arrayIndex = x + y * w;
      // int colorIndex = Byte.toUnsignedInt(data[arrayIndex]);
      int colorIndex = dataBuffer.getElem(arrayIndex);
      if (transIdx == colorIndex) {
        buf.setRGB(x, y, Color.RED.getRGB()); // 0xFF_FF_00_00);
      } else {
        buf.setRGB(x, y, colorModel.getRGB(colorIndex));
      }
    }
  }
  return buf;
}
View in GitHub: Java, Kotlin

解説

  • 左: オリジナルのGIF形式画像
  • 右: 透過色(クロマキー)をColor.REDで塗りつぶした画像
  • 下: GIF形式画像からカラーパレットを取得してセルが水平方向の次に垂直方向の順で並ぶ「ニュースペーパー・スタイル」レイアウトのJListに表示
    • カラーパレットはIndexColorModelから取得可能
      • IndexColorModelBufferedImage#getColorModel()で取得可能
    • 透過色が存在する場合はセルのフチを赤に設定
      • IndexColorModel#getTransparentPixel()で透過色のインデックスを取得可能

参考リンク

コメント