Search code examples
javaimagebufferedimagesnapshot

Center an image and the crop it to a fixed pixel size (java)


I'm currently working on a project were the user can draw an image and a small neural network then guesses the drawn(in Java, trust me I wanted to do it in Python). For this, I exported the canvas using snapshot. Now I want to center and crop a to a fixed size, let's say 50x50 pixel. Does Java have any methods for this?

public void guess(ActionEvent actionevent) {

    SnapshotParameters params = new SnapshotParameters();
    params.setFill(Color.TRANSPARENT);
    WritableImage image = new WritableImage((int)canvas.getWidth(),(int)canvas.getHeight());
    image = canvas.snapshot(params, null);
    BufferedImage bufferedImage = new BufferedImage((int)image.getWidth(),(int)image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    bufferedImage = SwingFXUtils.fromFXImage(image, null);
    String str = NNInterface.initNN(bufferedImage);
    outputText.setText(str);
}

}

Else I'd had to use double arrays or smth.

Thx


Solution

  • crop a to a fixed size, let's say 50x50 pixel. Does Java have any methods for this?

    Hmm, in your question you use the BufferedImage tag and the Image tag.

    In the BufferedImage class you find the getSubimage(...) method, which would allow you to crop the image.

    In the Image class you find the getScaledInstance(...) method, which allows you to scale the image.

    One would assume you read the API before asking a question. Maybe I don't understand the question?