简体   繁体   中英

How do I get the dimensions of a website image in Java without downloading it?

I'm looking for some code to get the dimensions of an image on a website in Java without having to download it first. The idea is that if the image is too big, I wouldn't download the file and would return an error message, so users don't input URLs that lead to files which are too big. It would take the height and the width of the image.

I know this code, from another user on StackOverflow, does this when you have a file on the system:

private Dimension getImageDim(final String path) {
Dimension result = null;
String suffix = this.getFileSuffix(path);
Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
if (iter.hasNext()) {
    ImageReader reader = iter.next();
    try {
        ImageInputStream stream = new FileImageInputStream(new File(path));
        reader.setInput(stream);
        int width = reader.getWidth(reader.getMinIndex());
        int height = reader.getHeight(reader.getMinIndex());
        result = new Dimension(width, height);
    } catch (IOException e) {
        log(e.getMessage());
    } finally {
        reader.dispose();
    }
} else {
    log("No reader found for given format: " + suffix));
}
return result; }

However, I have no idea how to translate that into something that can be used on a URL object.

Edit: I'm interested in the pixel width and the pixel height.

Sorry, I don't have code to show you but I can give general advice. Are you interested in the size of the image (width * height pixels) or the size of the file (bytes that you need to download)?

For getting the file size, you could try making an HTTP HEAD request to the remote server. This will return the headers without downloading the file - the ContentLength header may contain the size of the file. Or it may not, it is optional.

Getting the width and height in pixels requires downloading at least part of the file. These values are stored in the SOI (Start Of Image) record in the JPEG file format, which should be near the beginning of the file. You can download the first part of the image and parse the returned bytes looking for the SOI marker (0xFFD8).

The information you need is in the file you need to download.

I don't think you can do this without something on the server side to tell you the dimensions of the image. And this strikes me as being rather expensive for the server. Probably more expensive than just sending the image file ... unless you can find some way to extract an image's size metadata without fully reading it into memory on the server side.

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