问题
Is it possible to clone javafx.scene.image.Image
, not using pixel by pixel copying?
Or this is the only way?
回答1:
The code below copied from your link and put into a separate function is definitely not the "only" solution to the problem. It is definitely the best work-around that i personally know of. So here is the code for cut&paste:
copyImage
/**
* copy the given image to a writeable image
* @param image
* @return a writeable image
*/
public static WritableImage copyImage(Image image) {
int height=(int)image.getHeight();
int width=(int)image.getWidth();
PixelReader pixelReader=image.getPixelReader();
WritableImage writableImage = new WritableImage(width,height);
PixelWriter pixelWriter = writableImage.getPixelWriter();
for (int y = 0; y < height; y++){
for (int x = 0; x < width; x++){
Color color = pixelReader.getColor(x, y);
pixelWriter.setColor(x, y, color);
}
}
return writableImage;
}
Use in the context of an ImageView
If you have an ImageView that might have a readonly image this is how you get a copy "on the fly".
Platform.runLater() might be needed when calling the setImage ...
/**
* get the writeAbleImage (if available)
*
* @return the writeAbleImage or null if the image is not writeAble
*/
public WritableImage getWriteableImage() {
if (image instanceof WritableImage) {
return (WritableImage) image;
} else {
LOGGER.log(Level.INFO,"image is not writeable will create a writeable copy");
WritableImage copyImage=copyImage(image);
image=copyImage;
imageView.setImage(image);
return copyImage;
}
}
回答2:
Late answer, you probably made it so far.
My solution to this topic is like that.
// First create a cache image
planTiles[1][1] = new PlanTile(1, 1, "");
ImageView cache = planTiles[1][1].renderImage(); // timeconsuming operation
// In loop, use cache:
planTiles[iX][iY] = new PlanTile(iX, iY, "");
planTiles[iX][iY].setImage(cache.getImage());
回答3:
This is the solution:
writableImage = SwingFXUtils.toFXImage(SwingFXUtils.fromFXImage(sourceImage, null), null)
Full code:
public class JavaFXApplication extends Application {
@Override
public void start(Stage primaryStage) {
Image sourceImage = new Image("http://goo.gl/kYEQl");
ImageView imageView = new ImageView();
imageView.setImage(sourceImage);
ImageView destImageView = new ImageView();
//copying sourceImage
destImageView.setImage(SwingFXUtils.toFXImage(SwingFXUtils.fromFXImage(sourceImage, null), null));
VBox vBox = new VBox();
vBox.getChildren().addAll(imageView, destImageView);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 300);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
来源:https://stackoverflow.com/questions/30021841/how-to-clone-javafx-scene-image-image