简体   繁体   中英

java.net.MalformedURLException: unknown protocol: f

I am trying to get histogram of an image using this code Displaying a histogram of image data . Normally it works fine when input image given by url. But while I give image from local directory

private BufferedImage getImage() {
    try {
        return ImageIO.read(new URL(
            "F:/test.jpg"));
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
    return null;
}

it gives exception,

 java.net.MalformedURLException: unknown protocol: f 

How to resolve this exception and get Histogram of an image

F:/test.jpg is not a valid URL. For files the URL is file://F:/test.jpg where file is the protocol

The protocol is not valid.

If you need to load a file from the filesystem you need to use the file URI scheme

A file URI takes the form of file://host/path

where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name . If host is omitted, it is taken to be " localhost ", the machine from which the URL is being interpreted.

So the url should be:

file://F:/test.jpg

While the other answers will technically solve your problem, you shouldn't be using a URL for this. There are other signatures for the read function, one which takes a File and one which takes an InputStream instead , so you can use either of the following:

return ImageIO.read(new File("F:/test.jpg"));
// or
return ImageIO.read(new FileInputStream("F:/test.jpg"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM