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:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 * /*from ww  w  .  ja va2  s  .c  o  m*/
 * 
 ******************************************************************************************************************/
protected void assertImageMetadataSize(final ImageReader ir, final int width, final int height)
        throws IOException {
    final Dimension imageSize = new Dimension(ir.getWidth(0), ir.getHeight(0));
    final Dimension expectedSize = new Dimension(width, height);
    assertEquals("metadata image size: ", expectedSize, imageSize);
}

From source file:edu.ku.brc.specify.datamodel.busrules.AttachmentBusRules.java

protected void addImageAttributeIfNecessary() {
    if (browser != null) {
        Integer width = null;/*from w  ww .  j a  v a2  s .com*/
        Integer height = null;
        File file = new File(browser.getValue().toString());
        String mimeType = file == null ? null : AttachmentUtils.getMimeType(file.getName());
        boolean isImage = mimeType != null && mimeType.startsWith("image");
        if (isImage) {
            try {
                ImageInputStream iis = ImageIO.createImageInputStream(file);
                Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);

                if (readers.hasNext()) {
                    // pick the first available ImageReader
                    ImageReader reader = readers.next();
                    // attach source to the reader
                    reader.setInput(iis, true);

                    // read metadata of first image
                    //                      IIOMetadata metadata = reader.getImageMetadata(0);

                    width = reader.getWidth(0);
                    height = reader.getHeight(0);
                }
            } catch (IOException ex) {
                //XXX does this execption necessarily mean the file is bad?
                //XXX throw or log this exception
                ex.printStackTrace();
            }
        }
        //MultiView mvobj = formViewObj.getKids().get(0);
        FormViewObj aiafv = imageAttributeMultiView == null ? null
                : imageAttributeMultiView.getCurrentViewAsFormViewObj();
        if (aiafv != null) {
            //hide add/delete buttons. 
            aiafv.getNewRecBtn().setVisible(false);
            aiafv.getDelRecBtn().setVisible(false);
            if (isImage) {
                if (aiafv.getDataObj() == null) {
                    aiafv.getNewRecBtn().doClick();
                }
                System.out.println(browser.getValue() + "height " + height + " width " + width);
                try {
                    aiafv.setDataIntoUIComp("height", height);
                    aiafv.setControlChanged("height");
                    aiafv.setDataIntoUIComp("width", width);
                    aiafv.setControlChanged("width");
                } catch (Exception e) {
                    log.error("Unable set image attribute data. Controls may be missing from form definition");
                }
            } else {
                if (aiafv.getDataObj() != null) {
                    //delete the imageAttribute rec
                    //XXX suppress "confirm delete" dlg?
                    aiafv.getDelRecBtn().doClick();
                }
            }
        }
        setupImageAttributeView();
    }
}

From source file:net.naijatek.myalumni.modules.members.presentation.action.MaintainMemberAction.java

public ActionForward updateMemberAvatar(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    ActionMessages errors = new ActionMessages();
    String fileTypes = SystemConfigConstants.CONTENT_TYPE;
    String avatarDir = getSysProp().getValue("AVATAR.FILEPATH");
    MyAlumniUserContainer continer = getUserContainer(request);

    int maxFileSize = 0;
    int maxHeight = 0;
    int maxWidth = 0;
    String overwrite = "false";

    if (isCancelled(request)) {
        return mapping.findForward(BaseConstants.FWD_CANCEL);
    }/*from w  w  w .ja  v  a  2  s  .c o  m*/

    MemberVO token = getCurrentLoggedInUser(request);
    MemberForm memberForm = (MemberForm) form;

    if (!memberSecurityCheck(request, token)) {
        return mapping.findForward(BaseConstants.FWD_LOGIN);
    }

    //  Set Max Size
    try {
        maxFileSize = Integer.parseInt(getAppProp().getValue("avatar.image.size").trim());
    } catch (Exception e) {
        maxFileSize = 120000; // 120000 Bytes  = 120 KB
    }

    // Set Max Height
    try {
        maxHeight = Integer.parseInt(getAppProp().getValue("avatar.image.height").trim());
    } catch (Exception e) {
        maxHeight = 200; // 200 px 
    }

    // Set Max Width
    try {
        maxWidth = Integer.parseInt(getAppProp().getValue("avatar.image.width").trim());
    } catch (Exception e) {
        maxWidth = 200; // 200 px 
    }

    FormFile importFile = memberForm.getAvatarUpload();
    overwrite = StringUtil.safeString(memberForm.getAvatarUploadOverwrite());
    String importFileName = getCurrentLoggedInUser(request).getMemberUserName() + "."
            + getFileExtensionForImageReader(importFile.getFileName());
    int size = importFile.getFileSize();

    //--------------------  VALIDATE THE IMAGE -----------------------------------------
    // check width and heigh of image
    logger.debug(importFileName + " ext = " + getFileExtensionForImageReader(importFileName));
    Iterator readers = ImageIO.getImageReadersBySuffix(getFileExtensionForImageReader(importFileName));
    ImageReader reader = (ImageReader) readers.next();

    try {
        ImageInputStream iis = ImageIO.createImageInputStream(importFile.getInputStream());
        reader.setInput(iis, true);
        int width = reader.getWidth(0);
        int height = reader.getHeight(0);
        logger.debug(importFile.getFileName() + ": width=" + width + ", height=" + height);
        if (width > maxWidth || height > maxHeight) {
            errors.add(BaseConstants.WARN_KEY,
                    new ActionMessage("error.dimensions", width, height, maxWidth, maxHeight));
            saveMessages(request, errors);
            return mapping.getInputForward();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage() + ": can't open");
        errors.add(BaseConstants.FATAL_KEY, new ActionMessage("error.notreadable"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    // check file name
    if (importFileName.indexOf(" ") > -1) {
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename", importFileName));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    //boolean validImageName = false;
    /*      StringTokenizer st0 = new StringTokenizer(importFileName, ".");
          if (st0.hasMoreTokens()) {
            if (token.getMemberUserName().equals(st0.nextToken())) {
              //validImageName = true;
            }
            else{
              errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.fileusername", token.getMemberUserName(),importFileName ));
              saveMessages(request, errors);
              return mapping.getInputForward();
            }
          }*/

    File f = new File(avatarDir + importFileName);
    if (f.exists() && (overwrite.equalsIgnoreCase("false") || overwrite.equalsIgnoreCase(""))) {
        continer.setOverWriteAvatar(true);
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename.exist"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    if (size > maxFileSize) {
        errors.add(BaseConstants.WARN_KEY,
                new ActionMessage("error.filetoobig", String.valueOf(size), String.valueOf(maxFileSize)));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    boolean validImageExtension = false;
    StringTokenizer st = new StringTokenizer(fileTypes, ",");

    logger.debug("Current Type = " + importFile.getContentType());
    while (st.hasMoreTokens()) {
        if (importFile.getContentType().equalsIgnoreCase(st.nextToken())) {
            validImageExtension = true;
        }
    }

    // check file extension
    if (!validImageExtension) {
        errors.add(BaseConstants.WARN_KEY, new ActionMessage("error.imageext", String.valueOf(fileTypes)));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    // apend the file extension 
    //avatar = avatar + "." + importFile.getContentType();

    //-------------------------------------------------------------

    if (!uploadFromLocalDrive(importFile, importFileName, avatarDir)) {
        errors.add(BaseConstants.FATAL_KEY, new ActionMessage("errors.technical.difficulty"));
        saveMessages(request, errors);
        return mapping.getInputForward();
    }

    memService.updateMemberAvatar(importFileName, token.getMemberUserName(), getLastModifiedBy(request));
    continer.setOverWriteAvatar(false);
    continer.setAvatar(importFileName);
    MemberVO memberVO = memService.getMemberProfileByUserName(token.getMemberUserName());
    BeanUtils.copyProperties(memberForm, memberVO);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:net.naijatek.myalumni.framework.struts.MyAlumniDispatchAction.java

protected ActionMessages validateUploadFile(HttpServletRequest request, FormFile uploadedFile,
        String fileAllowedTypes, int maxFileSize, boolean validateHeight, int maxHeight, boolean validateWidth,
        int maxWidth) {

    ActionMessages msgs = new ActionMessages();

    String fileName = uploadedFile.getFileName();
    int fileSize = uploadedFile.getFileSize();

    if (fileName == null || fileName.length() == 0) {
        msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.notreadable"));
    } else {//from ww w .  j a  va 2 s. c  o m
        // Check for space in file name
        if (fileName.indexOf(" ") > -1) {
            msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.filename", fileName));
        }

        // check for file size
        if (fileSize > maxFileSize) {
            msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.filetoobig", String.valueOf(fileSize),
                    String.valueOf(maxFileSize)));
        }

        boolean validExtension = false;
        StringTokenizer st = new StringTokenizer(fileAllowedTypes, ",");
        while (st.hasMoreTokens()) {
            if (uploadedFile.getContentType().equalsIgnoreCase(st.nextToken())) {
                validExtension = true;
            }
        }

        if (!validExtension) {
            msgs.add(BaseConstants.WARN_KEY,
                    new ActionMessage("error.imageext", SystemConfigConstants.CONTENT_TYPE));
        } else {
            logger.debug(fileName + " ext = " + getFileExtensionForImageReader(fileName));
            Iterator readers = ImageIO.getImageReadersBySuffix(getFileExtensionForImageReader(fileName));
            ImageReader reader = (ImageReader) readers.next();

            try {
                ImageInputStream iis = ImageIO.createImageInputStream(uploadedFile.getInputStream());
                reader.setInput(iis, true);
                int width = reader.getWidth(0);
                int height = reader.getHeight(0);
                logger.debug(uploadedFile.getFileName() + ": width=" + width + ", height=" + height);

                if (validateHeight) {
                    if (height > maxHeight) {
                        msgs.add(BaseConstants.WARN_KEY,
                                new ActionMessage("error.heightdimensions", height, maxHeight));
                    }
                }

                if (validateWidth) {
                    if (width > maxWidth || height > maxHeight) {
                        msgs.add(BaseConstants.WARN_KEY,
                                new ActionMessage("error.widthdimensions", width, maxWidth));
                    }
                }
            } catch (IOException e) {
                msgs.add(BaseConstants.FATAL_KEY, new ActionMessage("error.notreadable"));
            }
        }
    }
    return msgs;
}

From source file:edu.emory.library.tast.images.admin.ImagesBean.java

public String uploadNewImage() {

    try {/* w ww.j a va  2s. co  m*/

        if (uploadedImage == null)
            return null;

        // check type
        String extension = (String) allowedTypes.get(uploadedImage.getContentType());
        if (extension == null)
            return null;

        // new filename
        File file = null;
        String fileName = null;
        String imageDir = AppConfig.getConfiguration().getString(AppConfig.IMAGES_DIRECTORY);
        do {
            fileName = new UidGenerator().generate() + "." + extension;
            file = new File(imageDir, fileName);
        } while (file.exists());

        // copy
        FileOutputStream imgFileStream = new FileOutputStream(file);
        int size = IOUtils.copy(uploadedImage.getInputStream(), imgFileStream);
        imgFileStream.flush();
        imgFileStream.close();

        // get image info
        Iterator readerIter = ImageIO.getImageReadersByFormatName(extension);
        ImageReader rdr = (ImageReader) readerIter.next();
        if (rdr == null)
            return null;
        rdr.setInput(ImageIO.createImageInputStream(file), true);

        // get width and height
        int width = rdr.getWidth(0);
        int height = rdr.getHeight(0);

        // replace current image
        imageWidth = width;
        imageHeight = height;
        imageSize = size;
        imageMimeType = uploadedImage.getContentType();
        imageFileName = fileName;

        // all ok
        uploadBoxShown = false;

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return null;
}

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

/**
 * Get the size of the file at the end of the URL
 *
 * Taken from: http://forums.sun.com/thread.jspa?threadID=528155&messageID=2537096
 *
 * @param artworkImage Artwork image to check
 * @param artworkWidth The width to check
 * @param artworkHeight The height to check
 * @param checkAspect Should the aspect ratio be checked
 * @return True if the poster is good, false otherwise
 *///ww w .  j av a 2 s  .c o m
@Override
public boolean validateArtwork(IImage artworkImage, int artworkWidth, int artworkHeight, boolean checkAspect) {
    @SuppressWarnings("rawtypes")
    Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
    ImageReader reader = (ImageReader) readers.next();
    int urlWidth;
    int urlHeight;
    float urlAspect;

    if (!artworkValidate) {
        return Boolean.TRUE;
    }

    if (artworkImage.getUrl().equalsIgnoreCase(Movie.UNKNOWN)) {
        return Boolean.FALSE;
    }

    try (InputStream in = new URL(artworkImage.getUrl()).openStream();
            ImageInputStream iis = ImageIO.createImageInputStream(in)) {
        reader.setInput(iis, Boolean.TRUE);
        urlWidth = reader.getWidth(0);
        urlHeight = reader.getHeight(0);
    } catch (IOException ex) {
        LOG.debug("ValidateArtwork error: {}: can't open URL", ex.getMessage());
        return Boolean.FALSE; // Quit and return a Boolean.FALSE poster
    }

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

    if (checkAspect && urlAspect > 1.0) {
        LOG.debug("{} rejected: URL is wrong aspect (portrait/landscape)", artworkImage);
        return Boolean.FALSE;
    }

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

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

    if (urlHeight < newArtworkHeight) {
        LOG.debug("{} rejected: URL height ({}) is smaller than artwork height ({})", artworkImage, urlHeight,
                newArtworkHeight);
        return Boolean.FALSE;
    }
    return Boolean.TRUE;
}

From source file:nl.b3p.viewer.print.PrintInfo.java

/**
 * Load image dimensions, ideally without decoding the entire image.
 *//*from   w w w  .j  av  a 2 s . c  o  m*/
private static Dimension getImageDimension(InputStream image) throws IOException {
    // http://stackoverflow.com/questions/1559253/java-imageio-getting-image-dimension-without-reading-the-entire-file

    ImageInputStream in = ImageIO.createImageInputStream(image);
    try {
        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();
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
    return null;
}

From source file:nova.core.wrapper.mc.forge.v17.wrapper.render.BWClientRenderManager.java

@SideOnly(Side.CLIENT)
@Override/*from ww  w .j  a va 2s  .  c  o m*/
public Vector2D getDimension(Texture texture) {
    ResourceLocation loc = toResourceLocation(texture);

    try {
        ImageInputStream in = ImageIO.createImageInputStream(
                Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream());
        Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Vector2D(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } catch (Exception e) {
        throw new RenderException("Couldn't load texture " + texture.getPath(), e);
    }
    return super.getDimension(texture);
}

From source file:nova.core.wrapper.mc.forge.v18.wrapper.render.BWClientRenderManager.java

@SideOnly(Side.CLIENT)
@Override/*from   w  w  w  .  j a va  2  s  . com*/
public Vector2D getDimension(Texture texture) {
    ResourceLocation loc = toResourceLocation(texture);

    try {
        ImageInputStream in = ImageIO.createImageInputStream(
                Minecraft.getMinecraft().getResourceManager().getResource(loc).getInputStream());
        Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Vector2D(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
    } catch (Exception e) {
        throw new RenderException("Couldn't load texture " + texture.getPath(), e);
    }
    return new Vector2D(16, 16);
}

From source file:org.apache.tika.parser.image.ImageParser.java

public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
        throws IOException, SAXException, TikaException {
    String type = metadata.get(Metadata.CONTENT_TYPE);
    if (type != null) {
        // If the old (pre-RFC7903) BMP mime type is given,
        //  fix it up to the new one, so Java is happy
        if (OLD_BMP_TYPE.toString().equals(type)) {
            type = MAIN_BMP_TYPE.toString();
        }//  w ww.  java  2s  . c  o m

        try {
            Iterator<ImageReader> iterator = ImageIO.getImageReadersByMIMEType(type);
            if (iterator.hasNext()) {
                ImageReader reader = iterator.next();
                try {
                    try (ImageInputStream imageStream = ImageIO
                            .createImageInputStream(new CloseShieldInputStream(stream))) {
                        reader.setInput(imageStream);

                        metadata.set(Metadata.IMAGE_WIDTH, Integer.toString(reader.getWidth(0)));
                        metadata.set(Metadata.IMAGE_LENGTH, Integer.toString(reader.getHeight(0)));
                        metadata.set("height", Integer.toString(reader.getHeight(0)));
                        metadata.set("width", Integer.toString(reader.getWidth(0)));

                        loadMetadata(reader.getImageMetadata(0), metadata);
                    }
                } finally {
                    reader.dispose();
                }
            }

            // Translate certain Metadata tags from the ImageIO
            //  specific namespace into the general Tika one
            setIfPresent(metadata, "CommentExtensions CommentExtension", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "markerSequence com", TikaCoreProperties.COMMENTS);
            setIfPresent(metadata, "Data BitsPerSample", Metadata.BITS_PER_SAMPLE);
        } catch (IIOException e) {
            // TIKA-619: There is a known bug in the Sun API when dealing with GIF images
            //  which Tika will just ignore.
            if (!(e.getMessage() != null && e.getMessage().equals("Unexpected block type 0!")
                    && type.equals("image/gif"))) {
                throw new TikaException(type + " parse error", e);
            }
        }
    }

    XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
    xhtml.startDocument();
    xhtml.endDocument();
}