JavaのImage関連って思いの外複雑でびっくりした。   古の方法である配列によるピクセル操作をやりたいだけなのにすごく苦労したぞ。   PixelGrabberとか、MemoryImageSourceとかWritableRasterとかかなり迷走した挙句、以下のシンプルな方法に行き着いた。   public void sample() throws IOException {    // PNG画像を読み込み  BufferedImage img1 = ImageIO.read( new File("ebi02.png") );    int w = img1.getWidth();  int h = img1.getHeight();    // ピクセルを配列として取得  int[] px = img1.getRGB( 0,0, w, h, null, 0, w );    // グレースケール化  for( int i=0; i<px.length; i++ )   px[i] = toGray( px[i] );    // 新しいBufferedImageを作成し、ピクセルを配列でセット  BufferedImage result = new BufferedImage( w, h, BufferedImage.TYPE_INT_RGB );  result.setRGB( 0,0, w, h, px, 0, w );    // BufferedImageをPNGとして保存  ImageIO.write( result, "png", new File("gray.png") ); }  private int toGray( int argb ) {    int a = (argb>>24) & 0xff;  int r = (argb>>16) & 0xff;  int g = (argb>>8 ) & 0xff;  int b = (argb    ) & 0xff;    int avr = ( r + g + b ) / 3;  int gray = avr & 0xff;    return (...
 
コメント
コメントを投稿