Home > Software design >  Invalid URL: unknown protocol: c when uploading a image to imageview javafx
Invalid URL: unknown protocol: c when uploading a image to imageview javafx

Time:11-08

I am trying to upload an image to an image view on java fx, I am getting the following error(runtime) when I selected an image.

Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c at javafx.scene.image.Image.validateUrl(Image.java:1121) at javafx.scene.image.Image.(Image.java:620) at me.siyum.schola.controller.AddStudentFromController.uploadStImageOnAction(AddStudentFromController.java:28) ... 41 more Caused by: java.net.MalformedURLException: unknown protocol: c

Code I am trying :

import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Circle;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;

public class AddStudentFromController {
    public Circle circleImage;
    public ImageView imgSt;

    public void uploadStImageOnAction(MouseEvent mouseEvent) {
        JFileChooser jFileChooser = new JFileChooser();
        jFileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter(
                ".IMAGE","jpg", "gif", "png");
        jFileChooser.addChoosableFileFilter(fileNameExtensionFilter);
        int result = jFileChooser.showSaveDialog(null);

        if(result == JFileChooser.APPROVE_OPTION){
            File selectedFile = jFileChooser.getSelectedFile();
            String absolutePath = selectedFile.getAbsolutePath();
            Image img = new Image(absolutePath);
            imgSt.setImage(img);

        }
    }
}

CodePudding user response:

The Image constructor expects a string representation of a URL. To get a URL for a File, use selectedFile.toURI().toURL(). To convert to a string representation in a robust way, call toExternalForm() on the URL. So you need

Image img = new Image(selectedFile.toURI().toURL().toExternalForm());

(You can almost certainly rely on selectedFile.toURI().toString(); the code above just feels marginally more robust.)

  • Related