ImageView not resizing image - imageview

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!

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.

Related

Enlarge Image Canvas

Is there a quick way using System.Drawing to quickly enlarge the image canvas of an .png image? (see example below). The caveat is the background might be transparent and I want to keep it transparent.
Edit: Needs to be in ASP .Net CORE
Alternatively, is there a way of putting the image on a white background that is slightly larger than the image?
After a few days of trial and error, I think I found something that works
Image overlayImage = //get your image here from file or url.
xloc = //x coord where to start overlay image.
yloc = //y coord where to start overlay image.
canvasWidth = //width of background canvas
canvasHeight = //height of background canvas
Bitmap baseImage = new Bitmap(canvasWidth, canvasHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (Graphics graphics = Graphics.FromImage(baseImage))
{
using (System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White))
{
graphics.FillRectangle(myBrush, new Rectangle(0, 0, canvasWidth, canvasHeight)); // white rectangle
}
graphics.CompositingMode = CompositingMode.SourceOver;
graphics.DrawImage(overlayImage, xloc, yloc);
} // graphics will be disposed at this line

Resizing ImageViews

I have a GridPane (4x5), all it's cells have as child an AnchorPane which cointains an ImageView. I need to resize the image so it fully cover the cell as soon as the gridPane (and thus it's cells) change size.
I managed to resize the image correctly when the size of the cell grows, but when the cell gets tinier the image doesn't resize back.
This leads into partially covering images of the confinant cells.
Can anyone explain what i'm doing wrong or give me the instruction to implement a proper resize?
This is my code:
ImageView image = new ImageView("/dice/" + draftList.get(i) + ".png");
AnchorPane pane = ((AnchorPane)(gridpane.getChildren().get(i)));
pane.getChildren().add(image);
fitToParent(image,pane);
//method in the same class
private void fitToParent(ImageView image, AnchorPane pane) {
image.fitWidthProperty().bind(pane.widthProperty());
image.fitHeightProperty().bind(pane.heightProperty());
}
You can try to use the setPreserveRatio(boolean) function of the ImageView class to true. This will allow you to keep the aspect ratio constant.
Eg:
ImageView iv = new ImageView(/*file path*/);
iv.setPreserveRatio(true);
Src: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/ImageView.html
Other than this you can also try to limit the resizable property to false or set the min width and height so that the image is not partially covered
Src: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/Region.html#resize-double-double-

How to save a high DPI snapshot of a JavaFX Canvas

I have created an image on a Canvas which is scaled down for display using a transformation. It is also in a ScrollPane which means only a part of the image is visible.
I need to take a snapshot of the entire canvas and save this as a high-resolution image. When I use Canvas.snapshot I get a Writable image of the visible part of the image after scaling down. This results in a low-res partial image being saved.
So how do I go about creating a snapshot which includes the entire canvas (not only the viewport of the scrollpane) and with the resolution before the transformation downwards?
I am not doing anything fancy currently, just this:
public WritableImage getPackageCanvasSnapshot()
{
SnapshotParameters param = new SnapshotParameters();
param.setDepthBuffer(true);
return packageCanvas.snapshot(param, null);
}
I did the following to get a canvas snapshot on a Retina display with a pixelScaleFactor of 2.0. It worked for me.
public static WritableImage pixelScaleAwareCanvasSnapshot(Canvas canvas, double pixelScale) {
WritableImage writableImage = new WritableImage((int)Math.rint(pixelScale*canvas.getWidth()), (int)Math.rint(pixelScale*canvas.getHeight()));
SnapshotParameters spa = new SnapshotParameters();
spa.setTransform(Transform.scale(pixelScale, pixelScale));
return canvas.snapshot(spa, writableImage);
}

JavaFX: maximum ImageView size

This may sound like a duplicate of Set maximum size for JavaFX ImageView but it's different.
I'd like to restrict the maximum size of an ImageView. Unfortunately, the only way to set the ImageView's size seems to be fitWidth and fitHeight which however enlarges the image if it's smaller than the fit values.
I tried setting fitWidth/fitHeight to 0/0 and wrap the ImageView into a pane with maxWidth set - no success (image is displayed in original size).
To me it seems as this is not achievable by JavaFX, however I can't believe it. But I couldn't find anything online. Are there any tricks/bugs/workarounds on this?
If you dont want the image to stretch, you can use:
setPreserveRatio(true);
Then you are able to fit width and height as you want
ImageView setPreserveRatio javadoc
In javadoc in this method there are the rules of scaling too
You just needed to add in if statement to set those larger than maxsize to a fixed size. The rest would remain their original size.
ImageView im = new ImageView();
im.setImage(image);
im.maxHeight(690 - 10);
int yoursize = 690;
if(im.maxHeight(690 - 10)> yoursize ){
im.setFitHeight(690- 10);
System.out.println("Fix Size : 690 ");
}
im.setPreserveRatio(true);
im.setSmooth(true);
im.setCache(true);
You can get the actual Image resource and query its width/height to use for the fit values:
Image image = imageView.getImage();
double nativeWidth = image.getWidth();
double nativeHeight = image.getHeight();

Resizing Image from a decoded ByteArray

I am trying to display a bytearray as a resized image. The Image is displaying correctly, but the sizing is off. Let me explain.
First I have the image data encoded so I need to decode the image data
// Instantiate decoder
var decoder:Base64Decoder = new Base64Decoder();
// Decode image data
decoded.decode(picture.data);
// Export data as a byteArray
var byteArray:ByteArray = decoder.toByteArray();
// Display image
var img:Image = new Image();
img.load(byteArray);
This works. The image is displayed correctly. However, if I hardcode the image (img) height the resized image is shown correctly, but within a box with the original image's dimensions.
For example, if the original image has a height of 300px and a width of 200px and the img.height property is set to 75; the resized image with height of 75 is shown correctly. But the resized image is shown in the upper left corner of the img container that is still set to a height of 300px and a width of 200px. Why does it do that? And what is the fix?
The best way to illustrate the problem is by placing the image inside a VBox and show the borders of the VBox. From the code block above, if I change the image height and set the image to maintain aspect ratio (which by default is set to true but I add it here for completeness). the problem becomes clear.
// Display image
var img:Image = new Image();
img.height = 75; // Hardcode image height (thumbnail)
img.maintainAspectRatio = true;
img.load(byteArray);
// Encapsulate the image inside a VBox to illustrate the problem
var vb:VBox = new VBox();
vb.setStyle('borderStyle', 'solid');
vb.setStyle('borderColor', 'red');
vb.setStyle('borderThickness', 2);
vb.addChild(img);
I have been working on this problem for days and cannot come up with a solution. Any ideas? What am I missing?
The workaround I used is as follows:
I created an event listener for the img display object. Then after the img has loaded, I manually set the height and width of the image. I know what I want the height (preHeight) to be so that is hardcoded. I then calculate the width and set that as the image width. For some reason I had to use the explicitHeight and explicitWidth properties to finally get the sizing right.
I hope this helps someone.
img.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
private function onCreationComplete(event:FlexEvent) : void
{
img.addEventListener(Event.COMPLETE, onImageLoadComplete);
}
private function onImageLoadComplete(event:Event) : void
{
var image:Image = event.currentTarget as Image;
var preHeight:Number = 0;
var h:uint = Bitmap(image.content).bitmapData.height;
var w:uint = Bitmap(image.content).bitmapData.width;
// Check height
preHeight = h > 170 ? 170 : h;
// Set the width
img.explicitWidth = (preHeight * w)/h;
img.explicitHeight = preHeight;
}

Resources