Search code examples
javajavafxthumbnails

Creating a image thumbnail in javafx


Can someone please help with some code for creating a thumbnail for a image in JavaFx.

I'm new at this, so a step by step explanation would be appreciated.


Solution

  • You can use an Image constructor to create a thumbnail image from a larger image, here is a sample from the Image javadoc:

    // load an image and resize it to width of 100 while preserving its
    // original aspect ratio, using faster filtering method
    // The image is downloaded from the supplied URL through http protocol
    Image image3 = new Image("http://sample.com/res/flower.png", 100, 0, false, false);
    

    What the Image constructor does is load the image and resize it, storing only the image pixels in memory, so it is I/O and processor intensive, but memory light.

    Note that if you do this a lot, it becomes pretty process expensive, which is why some image viewing systems save the thumbnail images to disk after they have created them, so that next time a thumbnail is needed it is read from disk rather than reading and resizing the entire original file. ImageIO can be used with SwingFXUtils to persist resized images to disk if you wish to do that.

    After you have created the resized Image, you can place it in an ImageView for display:

    ImageView imageView = new ImageView(image);
    

    You can use an ImageView to resize the view of images by manipulating the ImageView's viewport or fitHeight and fitWidth properties. If you have many thumbnail images, you would not wish to do that. Resizing the images in the ImageView rather than the Image constructor means that the Image backing the ImageView remains full size, which will quickly consume a lot of memory when you have a lot of images.