Example usage for javax.imageio ImageReader getHeight

List of usage examples for javax.imageio ImageReader getHeight

Introduction

In this page you can find the example usage for javax.imageio ImageReader getHeight.

Prototype

public abstract int getHeight(int imageIndex) throws IOException;

Source Link

Document

Returns the height in pixels of the given image within the input source.

Usage

From source file:at.gv.egiz.pdfas.common.utils.ImageUtils.java

public static Dimension getImageDimensions(InputStream is) throws IOException {
    ImageInputStream in = ImageIO.createImageInputStream(is);
    try {//ww  w  . java2s .  c  o  m
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
        throw new IOException("Failed to read Image file");
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:com.shending.support.CompressPic.java

public static void cut(String srcFile, String dstFile, int widthRange, int heightRange) {
    int x = 0;//from  w  w w  .  j  a v a2s  .co  m
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        newWidth = oldHeight * widthRange / heightRange;
        if (newWidth < oldWidth) {
            newHeight = oldHeight;
            x = (oldWidth - newWidth) / 2;
        } else {
            newWidth = oldWidth;
            newHeight = oldWidth * heightRange / widthRange;
            y = (oldHeight - newHeight) / 2;
        }
        Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
        param.setSourceRegion(rectangle);
        BufferedImage bi = reader.read(0, param);
        File file = new File(dstFile);
        ImageIO.write(bi, reader.getFormatName(), file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.shending.support.CompressPic.java

/**
 * ?//from w  ww.  j a  va  2  s  .  c om
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.jaeksoft.searchlib.util.ImageUtils.java

public static Dimension getDimensions(File imageFile) throws IOException {
    FileImageInputStream fiis = null;
    try {//ww w .  ja v  a 2s.c o m
        fiis = new FileImageInputStream(imageFile);
        ImageReader imageReader = ImageIO
                .getImageReadersBySuffix(FilenameUtils.getExtension(imageFile.getName())).next();
        imageReader.setInput(fiis);
        return new Dimension(imageReader.getWidth(0), imageReader.getHeight(0));
    } finally {
        IOUtils.close(fiis);
    }
}

From source file:com.occamlab.te.parsers.ImageParser.java

/**
 * Determines the height of the first image in an image file in pixels.
 * //from  w  w  w.  j  a v  a  2s .c  o  m
 * @param imageLoc
 *            the string location of the image (uri syntax expected)
 * @return int the image width in pixels, or -1 if unable.
 * @author Paul Daisey added 2011-05-13 to support WMTS ETS
 */
public static int getImageHeight(String imageLoc) {

    // Get the image as an InputStream
    InputStream is = null;
    try {
        URI imageUri = new URI(imageLoc);
        URL imageUrl = imageUri.toURL();
        is = imageUrl.openStream();
    } catch (Exception e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);

        return -1;
    }
    // Determine the image width
    try {
        // Create an image input stream on the image
        ImageInputStream iis = ImageIO.createImageInputStream(is);

        // Find all image readers that recognize the image format
        Iterator iter = ImageIO.getImageReaders(iis);

        // No readers found
        if (!iter.hasNext()) {
            return -1;
        }

        // Use the first reader
        ImageReader reader = (ImageReader) iter.next();
        reader.setInput(iis, true);
        int height = reader.getHeight(0);
        iis.close();

        return height;
    } catch (IOException e) {
        jlogger.log(Level.SEVERE, "getImageWidth", e);
        // The image could not be read
    }
    return -1;
}

From source file:com.moviejukebox.scanner.artwork.PosterScanner.java

/**
 * Read an URL and get the dimensions of the image using a specific image
 * type/* ww  w .j  ava 2 s  . c  o m*/
 *
 * @param imageUrl
 * @param imageType
 * @return
 */
public static Dimension getUrlDimensions(String imageUrl, String imageType) {
    Dimension imageDimension = new Dimension(0, 0);

    @SuppressWarnings("rawtypes")
    Iterator readers = ImageIO.getImageReadersBySuffix(imageType);

    if (readers.hasNext()) {
        ImageReader reader = (ImageReader) readers.next();

        try (InputStream in = new URL(imageUrl).openStream();
                ImageInputStream iis = ImageIO.createImageInputStream(in)) {
            reader.setInput(iis, Boolean.TRUE);
            imageDimension.setSize(reader.getWidth(0), reader.getHeight(0));
        } catch (IOException ex) {
            LOG.debug("getUrlDimensions error: {}: can't open url: {}", ex.getMessage(), imageUrl);
        } finally {
            reader.dispose();
        }
    }

    return imageDimension;
}

From source file:com.moviejukebox.scanner.artwork.PosterScanner.java

/**
 * Return the dimensions of a local image file
 *
 * @param imageFile/*from ww  w  .  j  a v  a 2s. c o m*/
 * @return Dimension
 */
public static Dimension getFileImageSize(File imageFile) {
    Dimension imageSize = new Dimension(0, 0);

    ImageReader reader = null;

    try (ImageInputStream in = ImageIO.createImageInputStream(imageFile)) {
        @SuppressWarnings("rawtypes")
        Iterator readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            reader = (ImageReader) readers.next();
            if (reader != null) {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            }
        }
    } catch (IOException | CMMException ex) {
        LOG.error("Failed to read image dimensions for {}", imageFile.getName());
        LOG.error("Error: {}", ex.getMessage());
        return imageSize;
    } finally {
        if (reader != null) {
            reader.dispose();
        }
    }

    return imageSize;
}

From source file:com.moviejukebox.scanner.artwork.FanartScanner.java

public static boolean validateArtwork(IImage artworkImage, int artworkWidth, int artworkHeight,
        boolean checkAspect) {
    @SuppressWarnings("rawtypes")
    Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
    ImageReader reader = (ImageReader) readers.next();
    int urlWidth, urlHeight;
    float urlAspect;

    if (!ARTWORK_VALIDATE) {
        return true;
    }/*from w  w w . j av  a  2s.c o m*/

    if (StringTools.isNotValidString(artworkImage.getUrl())) {
        return false;
    }

    try {
        URL url = new URL(artworkImage.getUrl());

        try (InputStream in = url.openStream(); ImageInputStream iis = ImageIO.createImageInputStream(in)) {
            reader.setInput(iis, true);
            urlWidth = reader.getWidth(0);
            urlHeight = reader.getHeight(0);
        }
    } catch (IOException error) {
        LOG.debug("ValidateFanart error: {}: can't open url", error.getMessage());
        return false; // Quit and return a false fanart
    }

    urlAspect = (float) urlWidth / (float) urlHeight;

    if (checkAspect && urlAspect < 1.0) {
        LOG.debug("ValidateFanart {} rejected: URL is portrait format", artworkImage);
        return false;
    }

    // Adjust fanart width / height by the ValidateMatch figure
    int newArtworkWidth = artworkWidth * (ARTWORK_VALIDATE_MATCH / 100);
    int newArtworkHeight = artworkHeight * (ARTWORK_VALIDATE_MATCH / 100);

    if (urlWidth < newArtworkWidth) {
        LOG.debug("{} rejected: URL width ({}) is smaller than fanart width ({})", artworkImage, urlWidth,
                newArtworkWidth);
        return false;
    }

    if (urlHeight < newArtworkHeight) {
        LOG.debug("{} rejected: URL height ({}) is smaller than fanart height ({})", artworkImage, urlHeight,
                newArtworkHeight);
        return false;
    }
    return true;
}

From source file:com.funambol.foundation.util.MediaUtils.java

/**
 * Creates the thumbnail.//from w  w w  .j a v a  2  s. c om
 *
 * @param imageFile the image file
 * @param thumbFile the empty thumbnail file
 * @param thumbX the width of the thumbnail
 * @param thumbY the height of the thumbnail
 * @param imageName the image file name with extension
 * @param tolerance the percentage of tolerance before creating a thumbnail
 * @return true is the thumbnail has been created, false otherwise
 * @throws IOException if an error occurs
 */
private static boolean createThumbnail(File imageFile, File thumbFile, int thumbX, int thumbY, String imageName,
        double tolerance) throws IOException {

    FileInputStream fileis = null;
    ImageInputStream imageis = null;

    Iterator readers = null;

    try {

        readers = ImageIO.getImageReadersByFormatName(imageName.substring(imageName.lastIndexOf('.') + 1));
        if (readers == null || (!readers.hasNext())) {
            throw new IOException("File not supported");
        }

        ImageReader reader = (ImageReader) readers.next();

        fileis = new FileInputStream(imageFile);
        imageis = ImageIO.createImageInputStream(fileis);
        reader.setInput(imageis, true);

        // Determines thumbnail height, width and quality
        int thumbWidth = thumbX;
        int thumbHeight = thumbY;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;
        int imageWidth = reader.getWidth(0);
        int imageHeight = reader.getHeight(0);

        //
        // Don't create the thumbnail if the original file is smaller
        // than required size increased by % tolerance
        //
        if (imageWidth <= (thumbWidth * (1 + tolerance / 100))
                && imageHeight <= (thumbHeight * (1 + tolerance / 100))) {

            return false;
        }

        double imageRatio = (double) imageWidth / (double) imageHeight;
        if (thumbRatio < imageRatio) {
            thumbHeight = (int) (thumbWidth / imageRatio);
        } else {
            thumbWidth = (int) (thumbHeight * imageRatio);
        }

        ImageReadParam param = reader.getDefaultReadParam();
        param.setSourceSubsampling(3, 3, 0, 0);

        BufferedImage bi = reader.read(0, param);

        Image thumb = bi.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_SMOOTH);

        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = thumbImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        graphics2D.drawImage(thumb, 0, 0, thumbWidth, thumbHeight, null);

        FileOutputStream fileOutputStream = new FileOutputStream(thumbFile);
        ImageIO.write(thumbImage, "jpg", fileOutputStream);

        thumb.flush();
        thumbImage.flush();
        fileOutputStream.flush();
        fileOutputStream.close();
        graphics2D.dispose();

    } finally {
        if (fileis != null) {
            fileis.close();
        }
        if (imageis != null) {
            imageis.close();
        }
    }

    return true;
}

From source file:com.qwazr.extractor.parser.ImageParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final Path path,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {

    final ImagePHash imgPhash = new ImagePHash();
    try (final ImageInputStream in = ImageIO.createImageInputStream(path.toFile())) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ParserFieldsBuilder result = resultBuilder.newDocument();
            ImageReader reader = readers.next();
            resultBuilder.metas().set(MIME_TYPE, "image/" + reader.getFormatName().toLowerCase());
            try {
                reader.setInput(in);//from ww w. ja  v  a2s .co m
                result.add(WIDTH, reader.getWidth(0));
                result.add(HEIGHT, reader.getHeight(0));
                result.add(FORMAT, reader.getFormatName());
                result.add(PHASH, imgPhash.getHash(reader.read(0)));
                IIOMetadata metadata = reader.getImageMetadata(0);
                if (metadata != null) {
                    String[] names = metadata.getMetadataFormatNames();
                    if (names != null)
                        for (String name : names)
                            browseNodes("META", metadata.getAsTree(name), result);
                }
            } finally {
                reader.dispose();
            }
        }
    }
}