简体   繁体   中英

Optimal solution for Image scaling where i need to preserve aspect ratio and retain good quality

So here is the problem: I am loading an image which is of unknown resolution. I need to scale it to 500px width to fit within my UI, preserving aspect ratio. The image quality must be good as i need to use it later, specifically to calculate an angle between two objects within the image.

So far i have tried the following:

In the following examples, we have an existing UI element ImageView imageView;

Method one: using scale on load in JavaFX image constructor:

public void setImage(String path){
    Image image = new Image(path, 550, 412, true, true);
    imageView.setImage(image);
}

This method achieves the required scaling, but lacks the quality required for an accurate calculation of angle later on.

Method two: using ImageView scaling to scale the displayed image:

public void setImage(String path){
    Image image = new Image(path);
    imageView.setFitWidth(550);
    imageView.setPreserveRatio(true);
    imageView.setImage(image);
}

This achieves the required quality and scaling, but the image contained within the view is not actually scaled, which means the calculations done later down the line are using an image not representative of the one being displayed.

Is there a way i can alter either of these solutions to work better or is there a better approach i can take? thank you.

You will have to use,

imageView.setSmooth(true);

to achieve better quality image after scaling.

EDIT:

It is because, the two methods are essentially different. The first method loads a bad quality image in the first place (with lesser pixels). One thing you can try is, to use AWT Image class for loading the image, using ImageIO , and call scaledImage = image.getScaledInstance(width, height) . Then use something like (pseudo code):

  1. create bufferedImage of scaled size
  2. bufferedImage.createGraphics() .drawImage(scaledImage, 0, 0, null)

to get scaled AWT Image. Then use SwingFXUtils to convert to image for FX application. This whole thing can probably be done in 3 lines of code by chaining the methods. I was able to achieve better quality this way in one of my previous projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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