问题
I am writing an application in JavaFX which makes amendments to a picture at the click of a button. So I have an ImageView and I have to extract the image from it, apply some changes and set it back. However, when I show an image which I get from the ImageView, it appears to be blank, just black screen. I wrote some test code, which represents that strange behavior.
public class Corrector extends Application {
@Override
public void start(Stage stage) {
try {
javafx.scene.image.ImageView imageView = new ImageView();
BufferedImage a = ImageIO.read(ClassLoader.getSystemResource("/image.jpg"));
javafx.scene.image.Image image = SwingFXUtils.toFXImage(a, null);
imageView.setImage(image);
BufferedImage backImg = new BufferedImage(a.getWidth(), a.getHeight(), a.getType());
SwingFXUtils.fromFXImage(imageView.getImage(), backImg);
ShowImages.showWindow(backImg, "Image from imageVIew", true);
stage.setTitle("ImageView");
stage.setWidth(1000);
stage.setHeight(500);
Scene scene = new Scene(new Group());
VBox root = new VBox();
root.getChildren().addAll(imageView);
scene.setRoot(root);
stage.setScene(scene);
stage.show();
} catch (Exception e) {
System.out.printf(e.getMessage());
}
}
public static void main(String[] args) {
launch(args);
}
}
When I run the application, "ImageView" screen contains image, which "Image frm ImageView" is blank. I would appreciate any suggestions.
回答1:
As the documentation of SwingFXUtils.fromFXImage says:
The optional BufferedImage parameter may be reused to store the copy of the pixels. A new BufferedImage will be created if the supplied object is null, is too small or of a type which the image pixels cannot be easily converted into.
In your case the type mismatches with the one SwingFXUtils.fromFXImage wants to use. So a new BufferedImage will be created and returned, containing the copied pixels, while your backImg stays untouched. You dont even have to offer an BufferedImage. Just set the second argument to null:
BufferedImage backImg = SwingFXUtils.fromFXImage(imageView.getImage(), null);
Some more information:
- You have defined the variable backImg twice. Remove the first definition because it is unused and unusable.
- You can even load your image by using the JavaFXImage-Constructor
:
Image fxFromFile = new Image(Corrector.class.getResourceAsStream("/image.png"));
来源:https://stackoverflow.com/questions/39729386/cant-get-image-from-imageview-in-javafx