How to crop and resize JavaFX Image?

时间秒杀一切 提交于 2019-12-05 20:52:01
James_D

There are a number of ways you can do this, depending on what information you have available at various points in the process.

If you know the size of the image on file before loading, and can thus compute the scale factor, you can actually scale it as you load it:

double requiredWidth = ... ;
double requiredHeight = ... ;
String imageURL = ... ;

Image image = new Image(imageURL, requiredWidth, requiredHeight, false, true);

The last two parameters are preserveRatio and smooth. The latter will force a slower but better quality rescaling algorithm.

Now you can just crop it to a new WritableImage as in the post you linked:

double x = ... ;
double y = ... ;
double width = ...;
double height = ... ;
WritableImage croppedImage = new WritableImage(image.getPixelReader(), x, y, width, height);

where x, y, width, and height defined the cropped region (in the scaled coordinates).

And then you can just draw the cropped image into your canvas:

graphicsContent.drawImage(croppedImage, canvasX, canvasY);

Anther approach is to load the whole image, and then use an ImageView to create a cropped, scaled view of it:

Image fullImage = new Image(imageURL);

// define crop in image coordinates:
Rectangle2D croppedPortion = new Rectangle2D(x, y, width, height);

// target width and height:
double scaledWidth = ... ;
double scaledHeight = ... ;

ImageView imageView = new ImageView(fullImage);
imageView.setViewport(croppedPortion);
imageView.setFitWidth(scaledWidth);
imageView.setFitHeight(scaledHeight);
imageView.setSmooth(true);

Now you can create a new image with the cropped version of the original image by taking a snapshot of the ImageView. To do this, you need to place the ImageView into an off-screen scene:

Pane pane = new Pane(imageView);
Scene offScreenScene = new Scene(pane);
WritableImage croppedImage = imageView.snapshot(null, null);

and then you can draw the cropped image into the canvas as before.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!