How can I load Computer Directory images in JAVAFX - image

I am trying to load my computer folder images into a wall of thumbnails. I read on a thread from another forum that ImageView "url" instance variable does not support system paths. I tried with the solution there, but it throws an exception: java.lang.OutOfMemoryError: Java heap space as it keeps reading the file.
another problem is it keeps giving me warning of using package javafx.ext -> SwingUtils.toFXImage method.
I have also tried to input the URL like that:
"file://localhost//Users/USER/Pictures/Camera/test/1.JPG"
I tried to display a number of images, but it always only displays 3 to 4 images.
I checked with the error function given from ImageView, it does not indicate that the reading of my images encountered an error.
Are there any alternatives?
Code
function load() {
println("RUNTIME {Runtime.getRuntime().maxMemory()}");
System.gc();
Runtime.getRuntime().freeMemory();
//MAC Folder PATH
var path: String = "/Users/username/Pictures/camera/test/1.JPG";;
var file: File = new File(path);
//http://download.oracle.com/docs/cd/E17802_01/javafx/javafx/1.3/docs/api/javafx.ext.swing/javafx.ext.swing.SwingUtils.html
//public toFXImage(image: java.awt.image.BufferedImage) : Image
//Creates a JavaFX Image from a BufferedImage.
img = SwingUtils.toFXImage(ImageIO.read(file));
}

It is not clear exactly what you are trying to do. If you are talking about JavaFX 2.0, the following code works. If you are loading a lot of images and need to conserve memory, you only have to create enough ImageView's for the number you want to display at one time. Then as you page through the images, you can swap out the Image object contained in the ImageView.
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
File file = new File("/System/Library/CoreServices/loginwindow.app/Contents/Resources/LogOut.png");
Image image = new Image(file.toURI().toString());
ImageView iv = new ImageView(image);
root.getChildren().add(iv);
primaryStage.setScene(scene);
primaryStage.show();
}

its simple: open a image with a browser and copy the whole url of the pic and paste it as a parameter of the Image object. DO NOT REMOVE "file///:" because this makes the image loadable. you will get your other logic from there. happy coding e.g
Image image = new Image("file:///C:/Users/Nigel/Desktop/my_image.png");
ImageView imgview = new ImageView(image);

None of the previous answers worked for me. However, this one, which I saw a while back but can't find an original link from, works flawlessly.
#Override
public void start(Stage primaryStage) throws Exception {
//create a pane to hold the image views
Pane pane = new HBox(10);
pane.setPadding(new Insets(5,5,5,5));
//create the image to be used!
Image image = new Image("/Content/vortex.jpg");
//set some custom properties and add an image
ImageView imageView = new ImageView(image);
imageView.setFitHeight(100);
imageView.setFitWidth(100);
pane.getChildren().add(imageView);
//add the second image view with this image and no custom properties
pane.getChildren().add(new ImageView(image));
ImageView imageView2 = new ImageView(image);
imageView2.setRotate(45);
pane.getChildren().add(imageView2);
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
The key is that when you create the image, START the path with a '/' (ie: "/Content/vortex.jpg"). Note that in this setup, the root folder is the src folder in most IDEs.

sorry if my answer came a little bit late but that was my approach and it works 100% wherever you are putting your file
1.assign your image to File
2.parse the File to URI
3.assign the uri.toString() to the image
ex code:
File imageFile = new File("path/to/image/outside/your/jar/awesomeless.jpg");
String fileLocation = imageFile.toURI().toString();
Image fxImage = new Image(fileLocation);
or you can simply put it all together like this:
Image fxImage = new Image(new File("path/.../awesomemore.jpg").toURI().toString());
and please if anyone knows a better approach let us know!

Another solution is to pass the InputStream into the Image class constructor; and is working...
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World");
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
java.io.FileInputStream fis = new FileInputStream("/System/Library/CoreServices/loginwindow.app/Contents/Resources/LogOut.png");
ImageView iv = new ImageView(new Image(fis));
root.getChildren().add(iv);
primaryStage.setScene(scene);
primaryStage.show();
}

Related

Rotation through images using JAVA FX

Essentially I'm trying to make a glowing warning image.
Starts just being a red triangle, but then emits a glow, then goes back to a red triangle.
But I'm trying to figure out a way to implement it.
I thought of using timelines, but it will only show the last picture, and stay on it.
I've replaced my Imaged with ones publicly available.
With these images it should come up "Number 1" for 2 seconds, "Number 2" for 2 seconds, "number 3" for 2 seconds, then go back to number 1 and repeat indefinitely.
Other than my way, if someone has a better way to make my objective happen in a different way with Java FX (That isn't too complex, I'm pretty new to Java FX). I'm all ears
Thanks again!
Here is the code I've fiddled with.
public class GlowEffect extends Application {
#Override
public void start(Stage primaryStage) {
Image img1 = new Image("http://clipart-library.com/images/dc9rEEbdi.jpg");
Image img2 = new Image("http://clipart-library.com/data_images/356167.png");
Image img3 = new Image("http://clipart-library.com/data_images/123556.png");
ImageView imgview1 = new ImageView();
imgview1.setX(0);
imgview1.setY(0);
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(2), e -> imgview1.setImage(img1)),
new KeyFrame(Duration.seconds(2), e -> imgview1.setImage(img2)),
new KeyFrame(Duration.seconds(2), e -> imgview1.setImage(img3))
);
timeline.setCycleCount(Animation.INDEFINITE);
Pane pane = new Pane(imgview1);
Scene scene = new Scene(pane, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
timeline.play();
}
public static void main(String[] args) {
launch(args);
}
}

How to have selectable images from image gallery in javafx?

I am making an image gallery. I am using javafx 8 along with scene builder for GUI. I want the user to have choice of selecting images from a gallery: I want to have clickable and selectable images in the gallery. I also want to note the sequence of those selected images, i.e. which one was selected first and which one was selected last. I have made the gallery but I was wondering what I would do to make the images clickable and get the images selected, noting their sequence? I don't want to use checkboxes with the images.
You can add a setOnMouseClicked handler on each ImageView.
Here is a code example of what I mean:
public class ClickableImage extends Application {
private ArrayList<String> clickedImages = new ArrayList<>();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
String imgUrl = getClass().getResource("image.png").toExternalForm();
assert imgUrl != null;
Image img = new Image(imgUrl);
assert img != null;
BorderPane root = new BorderPane();
ImageView imgView = new ImageView(img);
imgView.setUserData(imgUrl);
root.setCenter(imgView);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("ClickableImage");
primaryStage.show();
//-------------
imgView.setOnMouseClicked(e -> {
String clickedImgUrl = (String)((ImageView)e.getSource()).getUserData();
System.out.println("Image was clicked: " + clickedImgUrl);
clickedImages.add(clickedImgUrl);
});
}
}

JavaFX change the image in an imageView

Basically I have a method to load an Image from database into an imageView and a second method to change the image I'm sucessfully running both methods without getting an exception but after the setImage in changeImage() method what do I need to update and how (scene,stage) is it possible at all. I know that there is no method like repaint() in swing in javafx, so how do I approach this ?
public class MainMenuController implements Initializable {
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
private AnchorPane stck1;
#FXML
private AnchorPane openSecondWindow(ActionEvent event) throws Exception {
GUIController ctrl = new GUIController();
Stage stage = new Stage();
setStck1((AnchorPane) FXMLLoader.load(InteractiveFictionGame2.class.getResource("GUI.fxml")));
ImageView img_1 = new ImageView(ctrl.loadImg().getImage());
img_1.setPreserveRatio(true);
img_1.setSmooth(true);
img_1.setCache(true);
getStck1().getChildren().add(img_1);
Scene scene = new Scene(getStck1());
stage.setTitle("Interactive Fiction Game");
stage.setScene(scene);
stage.setFullScreen(true);
// stage.sizeToScene();
stage.show();
return getStck1();
}
public class GUIController implements Initializable {
#FXML
private TabPane tb1;
/**
* Initializes the controller class.
*
* #param url
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private ImageView img_1;
public ImageView loadImg() {
try {
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmnt.executeQuery(SQL);
rs.next();
fis = rs.getBinaryStream(4);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1 = new ImageView();
img_1.setImage(newImg);
rs.close();
stmnt.close();
con.close();
} catch (Exception e) {
System.out.println("Not working");
}
return img_1;
}
public void changeImage() {
..
fis = rs.getBinaryStream(1);
imgt = javax.imageio.ImageIO.read(fis);
Image newImg = SwingFXUtils.toFXImage(imgt, null);
img_1.setImage(newImg);
...
} catch (Exception e) {
System.out.println("Not working");
}
return img_1;
}
Your Issue
If you have a member node in your controller which you inject using #FXML, you should never create a new object instance using a new constructor and assign that new object to your existing reference. Instead just use the object which FXML created for you.
You have:
#FXML
private ImageView img_1;
That's fine.
Then in loadImg, you have:
img_1 = new ImageView();
img_1.setImage(newImg);
That is bad.
You already have an ImageView which the FXMLLoader created for you when you loaded your FXML document. The FXML Loader then assigned that ImageView to your img_1 reference because you used an #FXML annotation.
How to Fix it
So all you need to do is to stop creating new ImageViews and only write:
img_1.setImage(newImg);
And you are done.
Why it works
The Image property of ImageView is an observable property. The JavaFX system observes the Image property for any changes and if it changes, automatically updates the image displayed on the screen for the ImageView. You don't need to perform any repaint call (there is no such repaint routine to call in any case).
Background Reading
If you want to understand the JavaFX scene graph architecture better, read the Oracle tutorial on it:
Working with the JavaFX Scene Graph.
Some Tips
You can create a JavaFX image directly from an InputStream, you don't need to use ImageIO and SwingFXUtils for this task.
You can use a Task to communicate with a database and your application may be more responsive.
It is probably simpler to read the image from a file or over http rather than from a database.
Disclaimer
Besides the issue pointed out here, there may be other errors in code you have not provided which may prevent you from getting your application to work as you wish.
Java I graduate here:
In my JavaFX term project I had to update an imageView object upon a setOnAction Event (clicking a button). This allowed the program user to click through a series of pictures.
The following worked great:
First create your Image and ImageView instances:
Image imageObject = new Image();
ImageView imageViewObject = new ImageView();
Then down in the code a button event causes the (next) image to be assigned and updated as follows:
btn.setOnAction(e -> {
imageIndex++;
imageFilename = imageNamesArray.get(imageIndex);
imageObject = new Image(imageFilename);
imageViewObject.setImage(imageObject);
}
Note: The filename(s) in my project are jpg file (names) saved as String elements in an ArrayList(). The button click also increments the array index to the next jpg filename (and path or URL) and the new image would appear.
So as in the aforementioned answer you only create one ImageViewObject but you do reassign a new image to the image object "imageObject" each time.

PDFBox image size issues

I'm new to working with PdfBox and I'm having a small issue when displaying images. I'm able to import the image, which is sized at 800*900 pixels, and looks fine when viewed in an existing pdf at 100%. However when the resulting PDF is generated using the below code, the image becomes blurry, and the image extends beyond the boundaries of the A4 page.
Is there a different way of sizing/saving images so that they display correctly in pdfbox?
public class PDFtest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, COSVisitorException {
// TODO code application logic here
// Create a document and add a page to it
PDDocument document = new PDDocument();
PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont font = PDType1Font.HELVETICA_BOLD;
InputStream in = new FileInputStream(new File("img.jpg"));
PDJpeg img = new PDJpeg(document, in);
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page);
// Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
contentStream.drawImage(img, 10, 700);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(10, 650);
contentStream.drawString("Hello World");
contentStream.endText();
// Make sure that the content stream is closed:
contentStream.close();
// Save the results and ensure that the document is properly closed:
document.save("Hello World.pdf");
document.close();
}
I'd like to point out that as of 2.0 the contentStream.drawXObject function call in Victor's answer is deprecated. If you want to specify a width and height you should use contentStream.drawImage(image, x, y, width, height)
I had the same problem asked in this question, but the given answer is not right.
After some research I found a solution.
Instead of using the function drawImage use the function drawXObject
contentStream.drawXObject( img, 10, 700, 100, 100 );
Where the last two numbers specify the size of the image to be drawn.
For similar situation, for me, with PDF 2.0.11 and a tiff file of dimensions - 1600 x 2100 the following code perfectly fit the image in A4 (portrait) size. Not sure if PDFRectangle is okay with you.
I got this example straight from PDFBOX - Example
The only thing I tweaked/introduced is:
PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight()
Here is the full sample:
public static void main(String[] args) throws IOException
{
// if (args.length != 2)
// {
// System.err.println("usage: " + ImageToPDF.class.getName() + " <image> <output-file>");
// System.exit(1);
// }
String imagePath = "C:/FAX/sample.tiff";
String pdfPath = "C:/FAX/sample.pdf";
if (!pdfPath.endsWith(".pdf"))
{
System.err.println("Last argument must be the destination .pdf file");
System.exit(1);
}
try (PDDocument doc = new PDDocument())
{
PDPage page = new PDPage();
doc.addPage(page);
// createFromFile is the easiest way with an image file
// if you already have the image in a BufferedImage,
// call LosslessFactory.createFromImage() instead
PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
// draw the image at full size at (x=20, y=20)
try (PDPageContentStream contents = new PDPageContentStream(doc, page))
{
// draw the image at full size at (x=20, y=20)
contents.drawImage(pdImage, 0, 0, PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight());
// to draw the image at half size at (x=20, y=20) use
// contents.drawImage(pdImage, 20, 20, pdImage.getWidth() / 2, pdImage.getHeight() / 2);
}
doc.save(pdfPath);
System.out.println("Tiff converted to PDF succussfully..!");
}
}
Hope it helps.
If your intention is an A4 sized pic on a PDF, then i guess you find the actual size of typical A4 in pixels.
Also you should be aware of the extension of the picture that you want to view like jpg, gif, or bmp ...
from what I saw in your code, the dimensions of the picture are 10 X 700 which I believe is pretty small size.
contentStream.drawImage(img, 10, 700);
And the extension of the picture is : jpg
InputStream in = new FileInputStream(new File("img.jpg"));
check those and return for more info.
that's all.
good luck'''
As per the new API 2.0.x, one can use the PDRectangle to fetch Pdf page width and height. One can use PDPageContentStream to draw the image in accordance with PDF page.
For reference:
try (PDPageContentStream contents = new PDPageContentStream(pdDocument, pdPage)) {
final PDRectangle mediaBox = pdPage.getMediaBox();
final PDImageXObject pdImage = PDImageXObject.createFromFile(image, pdDocument);
contents.drawImage(pdImage, 0, 0, mediaBox.getWidth(), mediaBox.getHeight());
}

How to manage element precedence in JavaFX2?

Given this code:
#Override
public void start(final Stage stage)
{
final StackPane root = new StackPane();
final Region r1 = new Region(), r2 = new Region(), r3 = new Region();
r1.setMaxSize(400, 400);
r1.setStyle("-fx-background-color: yellow");
StackPane.setAlignment(r1, Pos.TOP_LEFT);
r2.setMaxSize(400, 400);
r2.setStyle("-fx-background-color: black");
StackPane.setAlignment(r2, Pos.TOP_RIGHT);
r3.setMaxSize(400, 400);
r3.setStyle("-fx-background-color: blue");
StackPane.setAlignment(r3, Pos.BOTTOM_CENTER);
root.getChildren().addAll(r1, r2 ,r3);
final Scene scene = new Scene(root, 600, 600);
stage.setScene(scene);
stage.show();
}
The output is the following:
Is there any easy way to control element precedence, without removing and re-adding all the elements that follow in the correct order? What I want to do, in this particular case, is make the element with the yellow background to overlay the other two, thus resulting in this:
The Scene Builder can move elements with CTRL+([|]). The only way that I can think of currently though, when it comes to doing this in code, is getting the children of the root element and doing pairs of remove/add in the correct order. Is there any other way, like, maybe, some property that manages overlay priority? Thank you.

Resources