Resize an image without reading it again from disk

2019-06-02 07:26发布

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);
    else
        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 :-)

2条回答
霸刀☆藐视天下
2楼-- · 2019-06-02 07:50

invariant was close to the final solution, credits for the final solution go to l2p in the oracle forum:

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(). So:

Image resizedImage = myImageView.snapshot(null, null); // after using myImageView.setFitHeight()/setFitWidth/( etc.

Bugfix:

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();
params.setFill(Color.TRANSPARENT); 
return imageView.snapshot(params, null); 

Hell, tricky this stuff ;-)

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-02 08:03

all you need is ImageView

load image one time in memory ,and then do manipulation on imageview when ever u need .

Sample Code :

//load image to memory
final static Image MY_IMAGE = new Image(path of image file);
//create different imageviews pointing to image in memory and do manipulations
ImageView myImage = new ImageView(MY_IMAGE);
myImage.setFitHeight(value);
myImage.setFitWidth(value);
查看更多
登录 后发表回答