如何克隆javafx.scene.image.Image?

时间:2015-05-04 02:40:53

标签: javafx

是否可以克隆javafx.scene.image.Image,而不是使用逐像素复制? 或者this是唯一的方法吗?

3 个答案:

答案 0 :(得分:0)

下面的代码从您的链接复制并放入单独的函数中,绝对不是解决该问题的“唯一”方法。这绝对是我个人所知的最佳解决方法。这是剪切和粘贴的代码:

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;
    }

在ImageView的上下文中使用

如果您的ImageView可能具有只读图像,这就是您“即时”获得副本的方式。

调用setImage时可能需要

Platform.runLater()...

/**
 * 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;
  }
}

答案 1 :(得分:-2)

迟到的答案,你可能到目前为止。

我对此主题的解决方案就是这样。

// 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());

答案 2 :(得分:-3)

这是解决方案:

writableImage = SwingFXUtils.toFXImage(SwingFXUtils.fromFXImage(sourceImage, null), null)

完整代码:

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);
}

}