John Baum
John Baum

Reputation: 3331

Determine file extension for image urls

Is there a reliable and fast way to determine the file extension of an image url? THere are a few options I see but none of them work consistently for images of the below format

https://cdn-image.blay.com/sites/default/files/styles/1600x1000/public/images/12.jpg?itok=e-zA1T

I have tried:

new MimetypesFileTypeMap().getContentType(url)

Results in the generic "application/octet-stream" in which case I use the below two:

Files.getFileExtension
FilenameUtils.getExtension

I would like to avoid regex when possible so is there another utility that properly gets past links that have args (.jpeg?blahblah). I would also like to avoid downloading the image or connection to the url in anyway as this should be a performant call

Upvotes: 2

Views: 573

Answers (2)

user4851
user4851

Reputation: 804

If you can trust that the URLs are not malformed, how about this:

FilenameUtils.getExtension(URI.create(url).getPath())

Upvotes: 2

Pieter Mantel
Pieter Mantel

Reputation: 123

Cant you just look at the file extension in the URL? so that would be something like:

public static String getFileExtension(String url) {
    int phpChar = url.length();
    for(int i = 0; i < url.length(); i++) {
        if(url.charAt(i) == '?') {
            phpChar = i;
            break;
        }
    }
    int character = phpChar - 1;
    while(url.charAt(character) != '.') character -= 1;
    return url.substring(character + 1, phpChar);
}

Maybe not the most elegant solution, but it works, even with the php ? in the url.

Upvotes: 0

Related Questions