ImageView not resizing image

孤者浪人 提交于 2019-12-12 01:29:27

问题


I want to use an ImageView to resize an image, however the image is not being resized:

ImageView imageView = new ImageView(image); 
imageView.setPreserveRatio(true);
imageView.setFitHeight(40);
System.out.println("imageview image width = " + imageView.getImage().getWidth());
System.out.println("imageview image height = " + imageView.getImage().getHeight());

The output is

imageview image width = 674.0
imageview image height = 888.0

However, the width should be 40. My ImageView is not attached to any scene and I also don't want to attach it, it shall only be used for image resizing. Is there any way to force the ImageView to resize its image, even though the ImageView is not attached to any scene? The reason I am using an ImageView for resizing is, that I want to resize an Image in RAM, without reading it again from the disk, please see this question for more details.

Thanks for any hint!


回答1:


Using an ImageView for resizing seems to be very hacky.

A better approach is to convert your Image into a BufferedImage and do the resizing the old way. (JavaFx does not (yet) provide an internal way to resize memory images)

int width = 500; // desired size
int height = 400;
Image original = ...; // fx image

BufferedImage img = new BufferedImage(
        (int)original.getWidth(),
        (int)original.getHeight(),
        BufferedImage.TYPE_INT_ARGB);

SwingFXUtils.fromFXImage(original, img);
BufferedImage rescaled = Scalr.rescaleImage(img, width, heigth);  // the actual rescale

// convert back to FX image
WritableImage rescaledFX = new WritableImage(width, heigth);
SwingFXUtils.toFXImage(rescaled, rescaledFX);

Where as Scalr is a nice library for resizing images in native java. Obviously, you can use other/simpler methods of rescaling, but the image quality won't be that nice.



来源:https://stackoverflow.com/questions/14924995/imageview-not-resizing-image

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