StackTips

How to Calculate Image Dimensions in Java

stacktips avtar

Written by

Editorial,  2 min read,  2.64K views, updated on Sept. 17, 2023

The following code snippet shows how to calculate image dimension in java by reading the file from specified path.

public static Dimension getImageDimension(final File path) {
    if (path == null) return null;

    Dimension result = null;
    String suffix = getFileExtension(path.toString());
    if (suffix.startsWith(".")) {
        suffix = suffix.substring(1);
    }

    final Iterator iterator = ImageIO.getImageReadersBySuffix(suffix);
    if (iterator.hasNext()) {
        final ImageReader reader = iterator.next();
        try {
            final ImageInputStream stream = new FileImageInputStream(path);
            reader.setInput(stream);
            int width = reader.getWidth(reader.getMinIndex());
            int height = reader.getHeight(reader.getMinIndex());
            result = new Dimension(width, height);
        } catch (IOException e) {
        } finally {
            reader.dispose();
        }
    } else {
        logger.error("No reader found for given format: " + suffix);
    }
    return result;
}

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!