CUBは子供の白熊

Java SE 8 実践プログラミングの練習問題を解く

第3章 ラムダ式を使ったプログラミング : 画像変換

3章の本文では、ラムダ式の応用として

画像の個々のピクセルの色の変換する

画像変換のサンプルが載っている。
このときに使用する関数型インターフェースはUnaryOperator<Color>である。

■ 変換前と変換後の画像を表示

public class ImageDemo extends Application {

    // 画像変換
    public static Image transform(Image in, UnaryOperator<Color> f) {
        int width  = (int)in.getWidth();
        int height = (int)in.getHeight();
        WritableImage out = new WritableImage(width, height);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                out.getPixelWriter().setColor(
                    x, y,
                    f.apply(in.getPixelReader().getColor(x, y))
                );
            }
        }
        return out;
    }

    // フォームの表示
    public void start(Stage stage) {
        Image image = new Image("queen-mary.png");
        Image brightenedImage = transform(image, Color::brighter);
        stage.setScene(new Scene(new HBox(
            new ImageView(image),
            new ImageView(brightenedImage)
        )));
        stage.show();
    }
}

■ 実行結果
f:id:ClosedUnBounded:20150225192205p:plain

単独のピクセルの変換では単純な変換しかできないが、これ以降の練習問題ではこの画像変換の拡張を扱う。