【发布时间】:2017-05-25 15:22:52
【问题描述】:
所以我还在学习 Java。现在正在学习JavaFX。
我有一张树的照片。我想尝试两种不同的方法。我使用的第一种方法是使用一元运算符将图像颜色变为灰色。
现在我想尝试第二种方法,使用我制作的ColourTransformer 接口,以获得一个 10 像素宽的灰色框来替换图像边框上的像素。
这就是我所做的。对于第二种方法,我不太确定如何指定像素。有什么建议吗?
这就是我所做的
public class ColourFilter extends Application {
//Using Unary Operator to transform image to grayscale - Method 1
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 static <T> UnaryOperator<T> compose(UnaryOperator<T> op1, UnaryOperator<T> op2) {
return t -> op2.apply(op1.apply(t));
}
//Using ColourTransformer interface to get 10 pixel wide gray frame replacing the pixels on the border of an image - Method 2
public static Image transform(Image in, ColourTransformer 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;
}
@FunctionalInterface
interface ColourTransformer {
Color apply(int x, int y, Color colorAtXY);
}
public void start(Stage stage) {
Image image = new Image("amazing-trees.jpg");
Image image2 = transform(image, Color::brighter);
Image image3 = transform(image2, Color::grayscale);
// alternative to two previous image transforms -- composition
//Image image3 = transform(image, compose(Color::brighter, Color::grayscale));
stage.setScene(new Scene(new VBox(
new ImageView(image),
// new ImageView(image2),
new ImageView(image3))));
stage.show();
}
}
【问题讨论】:
-
那不会编译,是吗?在
transform(Image, ColourTransformer)中你不需要f.apply(x, y, in.getPixelReader().getColor(x, y))吗?你能澄清一下问题是什么吗? -
当我添加第二种方法时它没有编译。我制作的第一种方法工作正常。所以第二种方法的目的是使用
ColourTransformer接口得到10像素宽的灰框替换图像边框上的像素。 -
编译错误是什么?我上面建议的更改不是解决了吗? (顺便说一句,您不认为包含诸如“它无法编译”之类的信息以及您遇到的编译错误会使某人更有可能回答这个问题吗……?)跨度>
-
哦,是的,注意到了。嗯,您提出的建议在第二种方法中一直存在。我会更新错误消息。
-
不,我提出的建议不存在。你有
f.apply(in.getPixelReader().getColor(x, y))。我认为你需要f.apply(x, y, in.getPixelReader().getColor(x, y))。 (这正是错误消息告诉你的。)