Example usage for javax.imageio IIOException getMessage

List of usage examples for javax.imageio IIOException getMessage

Introduction

In this page you can find the example usage for javax.imageio IIOException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:edu.harvard.iq.dvn.core.web.ExploreDataPage.java

private void writeImageFile(File fileIn, File pdfFileIn) {

    File imagePngFile = null;/* w  ww. j a  v a  2  s.c om*/

    try {
        String decoded = URLDecoder.decode(imageURL, "UTF-8");

        if (!decoded.isEmpty()) {
            URL imageURLnew = new URL(imageURL);

            try {
                BufferedImage image = ImageIO.read(imageURLnew);

                BufferedImage combinedImage = getCompositeImage(image);

                if (fileIn != null) {
                    ImageIO.write(combinedImage, "png", fileIn);
                }

                if (pdfFileIn != null) {
                    imagePngFile = File.createTempFile("pdfDownload", "png");
                    ImageIO.write(combinedImage, "png", imagePngFile);
                    Document convertPngToPdf = new Document();
                    PdfWriter.getInstance(convertPngToPdf, new FileOutputStream(pdfFileIn, true));
                    convertPngToPdf.open();
                    Image convertBmp = PngImage.getImage(imagePngFile.getAbsolutePath());
                    convertBmp.scaleToFit(530f, 500f);
                    convertPngToPdf.add(convertBmp);
                    convertPngToPdf.close();
                }
            } catch (IIOException io) {
                System.out.println(io.getMessage().toString());
                System.out.println(io.getCause().toString());
                System.out.println("IIOException " + imageURLnew);

            } catch (FontFormatException ff) {
                System.out.println("FontFormatException " + imageURLnew);

                System.out.println("FontFormatException " + ff.toString());
            }
        }

    } catch (UnsupportedEncodingException uee) {
        System.out.println("UnsupportedEncodingException ");
    } catch (MalformedURLException mue) {
        System.out.println("MalformedURLException ");
    } catch (IOException io) {
        System.out.println("IOException - outer ");
    } catch (DocumentException io) {
        System.out.println("IOException - document ");
        System.out.println(io.getMessage());
    } finally {
        if (imagePngFile != null && imagePngFile.exists()) {
            if (!FileUtil.keepTempFiles("core.web.ExploreDataPage")) {
                imagePngFile.delete();
            }
        }
    }
}

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 w w. j a  v a  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();
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    RenderedImage imageData = null;
    IIOException firstException = null;

    IIOMetadata iiometa = (IIOMetadata) info.getCustomObjects().get(ImageIOUtil.IMAGEIO_METADATA);
    boolean ignoreMetadata = (iiometa != null);
    boolean providerIgnoresICC = false;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream imgStream = ImageUtil.needImageInputStream(src);
    try {/*from  w  w w.  jav  a 2s .  com*/
        Iterator iter = ImageIO.getImageReaders(imgStream);
        while (iter.hasNext()) {
            ImageReader reader = (ImageReader) iter.next();
            try {
                imgStream.mark();
                ImageReadParam param = reader.getDefaultReadParam();
                reader.setInput(imgStream, false, ignoreMetadata);
                final int pageIndex = ImageUtil.needPageIndexFromURI(info.getOriginalURI());
                try {
                    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
                        imageData = reader.read(pageIndex, param);
                    } else {
                        imageData = reader.read(pageIndex, param);
                        //imageData = reader.readAsRenderedImage(pageIndex, param);
                        //TODO Reenable the above when proper listeners are implemented
                        //to react to late pixel population (so the stream can be closed
                        //properly).
                    }
                    if (iiometa == null) {
                        iiometa = reader.getImageMetadata(pageIndex);
                    }
                    providerIgnoresICC = checkProviderIgnoresICC(reader.getOriginatingProvider());
                    break; //Quit early, we have the image
                } catch (IndexOutOfBoundsException indexe) {
                    throw new ImageException("Page does not exist. Invalid image index: " + pageIndex);
                } catch (IllegalArgumentException iae) {
                    //Some codecs like com.sun.imageio.plugins.wbmp.WBMPImageReader throw
                    //IllegalArgumentExceptions when they have trouble parsing the image.
                    throw new ImageException("Error loading image using ImageIO codec", iae);
                } catch (IIOException iioe) {
                    if (firstException == null) {
                        firstException = iioe;
                    } else {
                        log.debug("non-first error loading image: " + iioe.getMessage());
                    }
                }
                try {
                    //Try fallback for CMYK images
                    BufferedImage bi = getFallbackBufferedImage(reader, pageIndex, param);
                    imageData = bi;
                    firstException = null; //Clear exception after successful fallback attempt
                    break;
                } catch (IIOException iioe) {
                    //ignore
                }
                imgStream.reset();
            } finally {
                reader.dispose();
            }
        }
    } finally {
        ImageUtil.closeQuietly(src);
        //TODO Some codecs may do late reading.
    }
    if (firstException != null) {
        throw new ImageException("Error while loading image: " + firstException.getMessage(), firstException);
    }
    if (imageData == null) {
        throw new ImageException("No ImageIO ImageReader found .");
    }

    ColorModel cm = imageData.getColorModel();

    Color transparentColor = null;
    if (cm instanceof IndexColorModel) {
        //transparent color will be extracted later from the image
    } else {
        if (providerIgnoresICC && cm instanceof ComponentColorModel) {
            // Apply ICC Profile to Image by creating a new image with a new
            // color model.
            ICC_Profile iccProf = tryToExctractICCProfile(iiometa);
            if (iccProf != null) {
                ColorModel cm2 = new ComponentColorModel(new ICC_ColorSpace(iccProf), cm.hasAlpha(),
                        cm.isAlphaPremultiplied(), cm.getTransparency(), cm.getTransferType());
                WritableRaster wr = Raster.createWritableRaster(imageData.getSampleModel(), null);
                imageData.copyData(wr);
                BufferedImage bi = new BufferedImage(cm2, wr, cm2.isAlphaPremultiplied(), null);
                imageData = bi;
                cm = cm2;
            }
        }
        // ImageIOUtil.dumpMetadataToSystemOut(iiometa);
        // Retrieve the transparent color from the metadata
        if (iiometa != null && iiometa.isStandardMetadataFormatSupported()) {
            Element metanode = (Element) iiometa.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
            Element dim = ImageIOUtil.getChild(metanode, "Transparency");
            if (dim != null) {
                Element child;
                child = ImageIOUtil.getChild(dim, "TransparentColor");
                if (child != null) {
                    String value = child.getAttribute("value");
                    if (value == null || value.length() == 0) {
                        //ignore
                    } else if (cm.getNumColorComponents() == 1) {
                        int gray = Integer.parseInt(value);
                        transparentColor = new Color(gray, gray, gray);
                    } else {
                        StringTokenizer st = new StringTokenizer(value);
                        transparentColor = new Color(Integer.parseInt(st.nextToken()),
                                Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
                    }
                }
            }
        }
    }

    if (ImageFlavor.BUFFERED_IMAGE.equals(this.targetFlavor)) {
        return new ImageBuffered(info, (BufferedImage) imageData, transparentColor);
    } else {
        return new ImageRendered(info, imageData, transparentColor);
    }
}

From source file:org.jajuk.ui.thumbnails.LastFmArtistThumbnail.java

/**
 * Long part of the populating process. Longest parts (images download) should
 * have already been done by the caller outside the EDT. we only pop the image
 * from the cache here./* w  w  w .jav a 2 s. c o  m*/
 */
private void preLoad() {
    try {
        // Check if artist is null
        String artistUrl = artist.getImageUrl();
        if (StringUtils.isBlank(artistUrl)) {
            return;
        }
        // Download thumb
        URL remote = new URL(artistUrl);
        // Download the picture and store file reference (to
        // generate the popup thumb for ie)
        fCover = DownloadManager.downloadToCache(remote);
        if (fCover == null) {
            Log.warn("Could not read remote file: {{" + remote.toString() + "}}");
            return;
        }
        BufferedImage image = ImageIO.read(fCover);
        if (image == null) {
            Log.warn("Could not read image data in file: {{" + fCover + "}}");
            return;
        }
        ImageIcon downloadedImage = new ImageIcon(image);
        // In artist view, do not reduce artist picture
        if (isArtistView()) {
            ii = downloadedImage;
        } else {
            ii = UtilGUI.getScaledImage(downloadedImage, 100);
        }
        // Free images memory
        downloadedImage.getImage().flush();
        image.flush();
    } catch (IIOException e) {
        // report IIOException only as warning here as we can expect this to
        // happen frequently with images on the net
        Log.warn("Could not read image: {{" + artist.getImageUrl() + "}} Cache: {{" + fCover + "}}",
                e.getMessage());
    } catch (UnknownHostException e) {
        Log.warn("Could not contact host for loading images: {{" + e.getMessage() + "}}");
    } catch (Exception e) {
        Log.error(e);
    }
}

From source file:org.medici.bia.controller.manuscriptviewer.IIPImageServerController.java

/**
 * //from w  w  w  .  j a v  a2s.  co m
 * @param imageName
 * @param thumbnailWidth
 * @param thumbnailFormat
 * @param response
 */
private void generateThumbnailImage(String imageName, Double thumbnailWidth, Integer imageQuality,
        String thumbnailFormat, HttpServletResponse httpServletResponse) {
    File imageFile = new File(
            ApplicationPropertyManager.getApplicationProperty("iipimage.image.path") + imageName);

    ImageInputStream imageInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    InputStream inputStream = null;

    try {
        if (imageFile.canRead()) {
            // Reading complete tiff information
            imageInputStream = ImageIO.createImageInputStream(imageFile);
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            imageFile = new File(ApplicationPropertyManager.getApplicationProperty("iipimage.image.path")
                    + ApplicationPropertyManager.getApplicationProperty("iipimage.image.notavailable"));
            if (imageFile.canRead()) {
                // Reading complete tiff information
                imageInputStream = ImageIO.createImageInputStream(imageFile);
            } else {
                logger.error("File " + imageFile.toString() + " is not present on filesystem. ");
            }
        }

        if (imageInputStream != null) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInputStream);
            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                reader.setInput(imageInputStream, false, true);

                BufferedImage page = null;
                if (reader.getNumImages(true) <= 2) {
                    logger.error(imageFile + " have " + reader.getNumImages(true)
                            + " level. Trying to render thumbnail image from level 1");
                    page = reader.read(0);
                } else {
                    page = reader.read(2);
                }

                if (page != null) {
                    RenderedOp thubmnailImage = null;
                    try {
                        double resizeFactor = thumbnailWidth / page.getWidth();

                        if (resizeFactor <= 1) {
                            ParameterBlock paramBlock = new ParameterBlock();
                            paramBlock.addSource(page); // The source image
                            paramBlock.add(resizeFactor); // The xScale
                            paramBlock.add(resizeFactor); // The yScale
                            paramBlock.add(0.0); // The x translation
                            paramBlock.add(0.0); // The y translation
                            RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_RENDERING,
                                    RenderingHints.VALUE_RENDER_QUALITY);
                            thubmnailImage = JAI.create("SubsampleAverage", paramBlock, qualityHints);
                        } else if (resizeFactor > 1) {
                            thubmnailImage = ScaleDescriptor.create(page, (float) resizeFactor,
                                    (float) resizeFactor, 0.0f, 0.0f,
                                    Interpolation.getInstance(Interpolation.INTERP_BICUBIC), null);
                        }

                        if ((thumbnailFormat != null) && (thumbnailFormat.toLowerCase().equals("jpeg"))) {
                            // replaced statement to control jpeg quality
                            // ImageIO.write(thubmnailImage, "jpeg",
                            // byteArrayOutputStream);
                            JPEGEncodeParam jpgparam = new JPEGEncodeParam();
                            jpgparam.setQuality(imageQuality);
                            ImageEncoder enc = ImageCodec.createImageEncoder("jpeg", byteArrayOutputStream,
                                    jpgparam);
                            enc.encode(thubmnailImage);
                        } else {
                            logger.error("Unmanaged thumbnail format " + thumbnailFormat);
                        }
                    } catch (IOException ioException) {
                        logger.error(ioException);
                    }
                }

                // preparing image for output
                inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

                // writing image to output
                httpServletResponse.setContentType("image/jpeg");
                IOUtils.copy(inputStream, httpServletResponse.getOutputStream());

                // Flushing request
                httpServletResponse.getOutputStream().flush();
            }
        } else {
            logger.error("File " + imageFile.toString() + " is not present on filesystem.");
        }
    } catch (IIOException iioException) {
        if (iioException.getMessage().equals("Unsupported Image Type")) {
            logger.error("Unsupported Image Type " + imageFile);
        } else {
            logger.error(iioException);
        }
    } catch (IOException ioException) {
        logger.error(ioException);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
        } catch (IOException ioException) {
        }
        try {
            if (imageInputStream != null) {
                imageInputStream.close();
            }
        } catch (IOException ioException) {
        }
    }
}