• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:ColorConvertOpで画像をグレースケールに変換
#navi(../)
RIGHT:Posted by [[terai]] at 2005-11-21
*ColorConvertOpで画像をグレースケールに変換 [#t5e7fcf3]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2005-11-21~
更新日:&lastmod;

#contents

**概要 [#p5efc4cd]
ColorConvertOpを使って画像をグレースケールに変換します。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#a2a42159]
#code{{
Image img = icon1.getImage();
BufferedImage source = new BufferedImage(
    img.getWidth(this), img.getHeight(this),
    BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = source.createGraphics();
g.drawImage(img, 0, 0, this);
g.dispose();
ColorConvertOp colorConvert = new ColorConvertOp(
    ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
BufferedImage destination = colorConvert.filter(source, null);
icon2 = new ImageIcon(destination);
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#s9c1238a]
用意したアイコンから、BufferedImageを作成し、これをColorConvertOp#filterメソッドを使ってグレースケールに変換しています。

上記のサンプルでは、ラベルをクリックすると元画像とグレースケール画像とが切り替わるようになっています。

----
以下のようにGrayFilter.createDisabledImageを使った場合よりきれいに変換できるようです。
#code{{
icon2 = new ImageIcon(GrayFilter.createDisabledImage(img));
}}

----
GrayFilterの代わりに、以下のようなRGBImageFilterを継承したフィルタを使う方法もあります。
#code{{
class MyGrayFilter extends RGBImageFilter {
  public MyGrayFilter() {
    canFilterIndexColorModel = true;
  }
  public int filterRGB(int x, int y, int rgb) {
    int a = (rgb >> 24) & 0xff;
    int r = (rgb >> 16) & 0xff;
    int g = (rgb >> 8) & 0xff;
    int b = rgb & 0xff;
    //http://ofo.jp/osakana/cgtips/grayscale.phtml
    int m = (2*r+4*g+b)/7; //NTSC係数による加重平均法(近似)
    return new Color(m,m,m,a).getRGB();
  }
}
FilteredImageSource fis = new FilteredImageSource(img.getSource(), new MyGrayFilter());
icon2 = new ImageIcon(createImage(fis));
}}

----
BufferedImage.TYPE_BYTE_GRAY で、BufferedImageを作成して複写してもグレースケールに変換できますが、透過色を使用している場合はすこし注意が必要なようです(参考:[[Color to Grayscale to Binary>http://forum.java.sun.com/thread.jspa?threadID=5138820]])。
BufferedImage.TYPE_BYTE_GRAY で、BufferedImageを作成して複写してもグレースケールに変換できますが、透過色を使用している場合はすこし注意が必要なようです(参考:[[Swing - Color to Grayscale to Binary>http://forums.sun.com/thread.jspa?threadID=5138820]])。

#code{{
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
bi.createGraphics().drawImage(img, 0, 0, this);
}}

**参考リンク [#wb3b736d]
-[[Image Color Gray Effect : Java examples (example source code) » 2D Graphics GUI » Image>http://www.java2s.com/Code/Java/2D-Graphics-GUI/ImageColorGrayEffect.htm]]
-[[opus-i | シンプル素材 テンプレート 音楽素材>http://opus-i.biz/]]
-%%[[フィルタによる半透明な画像の作成>http://numata.aquasky.jp/programming/java/graphics/FilteringImage.html]]%%
-[[osakana.factory - グレースケールのひみつ>http://ofo.jp/osakana/cgtips/grayscale.phtml]]
-[[プログラマメモ2: グレースケール>http://programamemo2.blogspot.com/2007/08/blog-post_21.html]]

**コメント [#i2aa6deb]
- リンクを参考にしてRGBImageFilterを使うサンプルを修正しました。 -- [[terai]] &new{2007-08-21 (火) 13:06:10};
- グレイスケールからグレースケールに変更。 -- [[terai]] &new{2008-01-10 (木) 14:31:00};

#comment