Forum Stats

  • 3,839,768 Users
  • 2,262,532 Discussions


Resize an image without reading it again from disk?

990159 Member Posts: 22
edited Feb 18, 2013 10:16AM in JavaFX 2.0 and Later
0 down vote favorite

I need to resize an image based on it's longest side, e.g. longest side - which can be width or height - should be only 100 pixels long.

Currently I am using this method:
private Image resizeImageByLongestSide(File imageFile, int lengthLongestSide)
    String uri ="file:" + imageFile.getAbsolutePath();
    Image image = new Image(uri); // raed to determine width/height

    // read image again for resizing
    if(image.getWidth() >= image.getHeight())
        return new Image(uri, lengthLongestSide, 0, true, false);
        return new Image(uri, 0, lengthLongestSide, true, false);
So, first the image has to be read by disk to figure out which side is the longest side, than it has again to be read from the disk, because resizing seems only possible by using the Image constructor... Any hint/improvement on this? Thanks :-)

Note: I already tried an ImageView for resizing the image, however [while an ImageView is not attached to a scene it seems not to resize the image|] ):


  • l2p
    l2p Member Posts: 14
    ImageView does not alter the actual Image whether it is in a scene or not. It only renders a visible node from the given image. If you want it to render a new Image from its current visible state you have to make a snapshot().
    public Image scaleImage(final Image sourceImage, final int longestSide)
    	final ImageView view = new ImageView(sourceImage);
    	return view.snapshot(null, null);
    This should work.
  • 990159
    990159 Member Posts: 22
    edited Feb 18, 2013 9:14AM
    Works perfect, thank you very much! And it even leaves the source/original image untouched, very useful for my use case.

    Edited by: srynoname on 18.02.2013 06:14
  • 990159
    990159 Member Posts: 22

    Transparency is lost with the current approach, because default control (herE: imageview) background is white. screenshot of transparency (from our image) on white gives white, so we loose the original transparency. fix for this: set the background itself to transparent.

    So, the fixed code:
    SnapshotParameters params = new SnapshotParameters();
    return imageView.snapshot(params, null); 
This discussion has been closed.