简体   繁体   English

如何调整JavaFX图像的大小?

[英]How can I resize a JavaFX image?

I have a javafx.scene.image.Image , and I would like to resize it, eg scaling it by a given factor. 我有一个javafx.scene.image.Image ,我想调整它的大小,例如按给定因子缩放它。 How to do that (without converting to BufferedImage ), and what are the options regarding quality and performance (such as interpolation types)? 怎么做(没有转换为BufferedImage ),有关质量和性能的选项有哪些(例如插值类型)?

There are several questions that look similar, but I couldn't find anybody who asked the same thing. 有几个问题看起来很相似,但我找不到任何提出相同问题的人。 The key point is that the input is an Image object (and scaling factor) and the desired output is another Image object. 关键点是输入是Image对象(和缩放因子),所需的输出是另一个Image对象。

The simplest way is something like: 最简单的方法是:

public Image scale(Image source, int targetWidth, int targetHeight, boolean preserveRatio) {
    ImageView imageView = new ImageView(source);
    imageView.setPreserveRatio(preserveRatio);
    imageView.setFitWidth(targetWidth);
    imageView.setFitHeight(targetHeight);
    return imageView.snapshot(null, null);
}

A minimal amount of control over the speed/smoothness of the scaling algorithm is made available via a call to imageView.setSmooth(...); 通过调用imageView.setSmooth(...);可以对缩放算法的速度/平滑度进行最小程度的控制imageView.setSmooth(...); with the value true using a slower algorithm with better smoothing and false using a faster algorithm with less smoothing. 与价值true使用较慢的算法具有更好的平滑和false使用更快的算法用更少的平滑。

Without converting it to BufferedImage you will need to implement scaling algorithm and do something like: 如果不将其转换为BufferedImage您将需要实现缩放算法并执行以下操作:

Image source = ...
WritableImage target = new WritableImage(targetWidth, targetHeight)

scale(target, source)

(Note that javafx.scene.image.WritableImage is extended from Image and intended for purposes of creating image from memory data.) (请注意, javafx.scene.image.WritableImage是从Image扩展的,用于从内存数据创建图像。)

The scale function will read pixels from source image PixelReader and, after doing scaling operation on each individual source pixel, will write pixels into target image PixelWriter . scale功能将从source图像PixelReader读取像素,并且在对每个单独的源像素执行缩放操作之后,将像素写入target图像PixelWriter Actual implementation will depend on selected algorithm. 实际实施将取决于所选算法。

In other words you will need to implement your own scaling algorithm. 换句话说,您需要实现自己的缩放算法。

Please note that this is not trivial operation as you will need to acount for upsampling (target is larger) and downsampling (target is smaller). 请注意,这不是一个简单的操作,因为您需要进行上采样(目标更大)和下采样(目标更小)。 You can find a list of image scaling algorithms on Wikipedia 您可以在Wikipedia上找到图像缩放算法列表

One of the simplest algorithms is Nearest neighbour but it produces some artifacts. 最简单的算法之一是最近邻,但它会产生一些伪影。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM