CUBは子供の白熊

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

第3章 ラムダ式を使ったプログラミング : 問題 5 : 座標を考慮した画像変換

問題

画像変換を、色だけでなく座標も参照するように拡張する。
そのために以下の関数型インターフェースを導入する。

@FunctionalInterface
interface ColorTransformer {
    Color apply(int x, int y, Color colorAtXY);
}

画像の周りの10ピクセルを灰色の枠で置き換える画像変換を実装せよ

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

解答

transformメソッドは、以下のようになる。

transformメソッド

public static Image transform(Image in, ColorTransformer 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(x, y, in.getPixelReader().getColor(x, y))
            );
        }
    }
    return out;
}

transformメソッドの呼び出し

public void start(Stage stage) throws Exception {
    Image image = new Image("queen-mary.png");
    int width  = (int)image.getWidth();
    int height = (int)image.getHeight();
    Image image2 = transform(
        image,
        (x, y, c) ->
            x < 10 || y < 10 || x >= width - 10 || y >= height - 10 ? Color.GRAY: c
    );
    stage.setScene(new Scene(new HBox(new ImageView(image), new ImageView(image2))));
    stage.show();
}

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