user1406177
user1406177

Reputation: 1370

Resize existing JavaFX image

I have to load images:

Image image = new Image(f.toURI().toString(), width, height, true, true);

Since I also have tiffs, I have to load them differently using JAI:

BufferedImage read = ImageIO.read(f);
Image image = SwingFXUtils.toFXImage(read, null);

Now I have an Image object, but it has the wrong size. Image offers no methods to resize the object. How do I resize is so it has the same size as if I would load a jpg or png with the shown line?

Upvotes: 0

Views: 975

Answers (1)

James_D
James_D

Reputation: 209225

Seems like there should be an easier way to do this, but you can try:

BufferedImage read = ImageIO.read(f);
int[] pixels = new int[width * height] ;
PixelGrabber grabber = new PixelGrabber(read.getScaledInstance(width, height, Image.SCALE_SMOOTH), 
    0, 0, width, height, 0, pixels, width);
grabber.grabPixels();
WritableImage fxImage = new WritableImage(width, height);
PixelWriter pw = fxImage.getPixelWriter();
pw.setPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);

Now fxImage is a javafx.scene.image.Image that has dimensions width by height.

Be aware that PixelGrabber.grabPixels() is a blocking call, so you will need to handle InterruptedExceptions. For large images you might want to do this in a Task executed on a background thread, so as not to block the FX Application Thread.

Upvotes: 2

Related Questions