CUBは子供の白熊

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

第3章 ラムダ式を使ったプログラミング : 問題 6 : パラメータ付き画像変換

問題 6

画像変換で、UnaryOperator<Color>ではなくBiFunction<Color, T, Color>を引数にとる transform メソッドを実装せよ

画像変換のオリジナルは 第3章 ラムダ式を使ったプログラミング : 画像変換 - CUBは子供の白熊 を参照

解答

これで変換関数にパラメータを渡すことができる。

transformメソッド

public static <T> Image transform(Image in, BiFunction<Color, T, Color> f, T arg) {
    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), arg)
            );
        }
    }
    return out;
}

例として、明度をパラメータとする明度変換を実装する。

transformメソッドの呼び出し

public void start(Stage stage) throws Exception {
    Image image = new Image("queen-mary.png");
    Image image2 = transform(
        image,
        (c, brightness) -> c.deriveColor(0.0, 1.0, brightness, 1.0),
        Math.sqrt(2.0)
    );
    stage.setScene(new Scene(new HBox(new ImageView(image), new ImageView(image2))));
    stage.show();
}

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