List of usage examples for javax.imageio ImageReader getImageMetadata
public abstract IIOMetadata getImageMetadata(int imageIndex) throws IOException;
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
private IIOMetadata getImageMetadata(ImageReader ir) throws ImageInterpreterException { IIOMetadata md = null;/*from www .ja v a2 s . com*/ Node treeNode = null; try { md = ir.getImageMetadata(0); String formatName = md.getNativeMetadataFormatName(); treeNode = md.getAsTree(formatName); } catch (Error e) { throw new ImageInterpreterException("Error when attempting to parse image metadata: " + e.toString()); } catch (Exception e) { throw new ImageInterpreterException("Error when attempting to parse image metadata: " + e.toString()); } if ((treeNode == null) || (treeNode.getChildNodes() == null)) { throw new ImageInterpreterException("Image metadata Node is null or empty"); } return md; }
From source file:com.occamlab.te.parsers.ImageParser.java
private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger) throws Exception { if (nodes.getLength() == 0) { return null; }/*w w w . j av a 2 s .c om*/ String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08 // PwD BufferedImage image = reader.read(frame); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // System.out.println(node.getLocalName()); if (node.getLocalName().equals("type")) { node.setTextContent(formatName); // 2011-09-08 PwD was // reader.getFormatName().toLowerCase() } else if (node.getLocalName().equals("height")) { node.setTextContent(Integer.toString(image.getHeight())); } else if (node.getLocalName().equals("width")) { node.setTextContent(Integer.toString(image.getWidth())); } else if (node.getLocalName().equals("metadata")) { try { // 2011--08-23 PwD IIOMetadata metadata = reader.getImageMetadata(frame); if (metadata != null) { String format = ((Element) node).getAttribute("format"); if (format.length() == 0) { format = metadata.getNativeMetadataFormatName(); } Node tree = metadata.getAsTree(format); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(tree), new DOMResult(node)); } } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); String format = reader.getFormatName().toLowerCase(); String formatEltName = "javax_imageio_" + format + "_1.0"; Element formatElt = doc.createElement(formatEltName); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(formatElt), new DOMResult(node)); } } else if (node.getLocalName().equals("model")) { int imagetype = -1; String model = ((Element) node).getAttribute("value"); if (model.equals("MONOCHROME")) { imagetype = BufferedImage.TYPE_BYTE_BINARY; } else if (model.equals("GRAY")) { imagetype = BufferedImage.TYPE_BYTE_GRAY; } else if (model.equals("RGB")) { imagetype = BufferedImage.TYPE_3BYTE_BGR; } else if (model.equals("ARGB")) { imagetype = BufferedImage.TYPE_4BYTE_ABGR; } else { model = "CUSTOM"; } ((Element) node).setAttribute("value", model); BufferedImage buffImage = image; if (image.getType() != imagetype && imagetype != -1) { buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype); Graphics2D g2 = buffImage.createGraphics(); ImageTracker tracker = new ImageTracker(); boolean done = g2.drawImage(image, 0, 0, tracker); if (!done) { while (!tracker.done) { sleep(50); } } } processBufferedImage(buffImage, formatName, node.getChildNodes()); } else if (node.getLocalName().equals("transparency")) { // 2011-08-24 // PwD int transparency = image.getTransparency(); String transparencyName = null; switch (transparency) { case Transparency.OPAQUE: { transparencyName = "Opaque"; break; } case Transparency.BITMASK: { transparencyName = "Bitmask"; break; } case Transparency.TRANSLUCENT: { transparencyName = "Translucent"; break; } default: { transparencyName = "Unknown"; } } node.setTextContent(transparencyName); } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08 // PwD String base64Data = getBase64Data(image, formatName, node); node.setTextContent(base64Data); } else { logger.println("ImageParser Error: Invalid tag " + node.getNodeName()); } } } return null; }
From source file:org.dita.dost.writer.ImageMetadataFilter.java
private Attributes readMetadata(final URI imgInput) { logger.info("Reading " + imgInput); final XMLUtils.AttributesBuilder a = new XMLUtils.AttributesBuilder(); try {/*from w w w . j a va 2 s .c om*/ InputStream in = null; ImageReader r = null; ImageInputStream iis = null; try { in = getInputStream(imgInput); iis = ImageIO.createImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(iis); if (!i.hasNext()) { logger.info("Image " + imgInput + " format not supported"); } else { r = i.next(); r.setInput(iis); final int imageIndex = r.getMinIndex(); a.add(DITA_OT_NS, ATTR_IMAGE_WIDTH, DITA_OT_PREFIX + ":" + ATTR_IMAGE_WIDTH, "CDATA", Integer.toString(r.getWidth(imageIndex))); a.add(DITA_OT_NS, ATTR_IMAGE_HEIGHT, DITA_OT_PREFIX + ":" + ATTR_IMAGE_HEIGHT, "CDATA", Integer.toString(r.getHeight(imageIndex))); final Element node = (Element) r.getImageMetadata(0).getAsTree("javax_imageio_1.0"); final NodeList hs = node.getElementsByTagName("HorizontalPixelSize"); if (hs != null && hs.getLength() == 1) { final float v = Float.parseFloat(((Element) hs.item(0)).getAttribute("value")); final int dpi = Math.round(MM_TO_INCH / v); a.add(DITA_OT_NS, ATTR_HORIZONTAL_DPI, DITA_OT_PREFIX + ":" + ATTR_HORIZONTAL_DPI, "CDATA", Integer.toString(dpi)); } final NodeList vs = node.getElementsByTagName("VerticalPixelSize"); if (vs != null && vs.getLength() == 1) { final float v = Float.parseFloat(((Element) vs.item(0)).getAttribute("value")); final int dpi = Math.round(MM_TO_INCH / v); a.add(DITA_OT_NS, ATTR_VERTICAL_DPI, DITA_OT_PREFIX + ":" + ATTR_VERTICAL_DPI, "CDATA", Integer.toString(dpi)); } } } finally { if (r != null) { r.dispose(); } if (iis != null) { iis.close(); } if (in != null) { in.close(); } } } catch (final Exception e) { logger.error("Failed to read image " + imgInput + " metadata: " + e.getMessage(), e); } return a.build(); }
From source file:nl.b3p.imagetool.ImageTool.java
/** * Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage//from w ww.java2 s . c o m * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(InputStream is, String mime) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + baos.toString()); throw new Exception( "Response from server not understood (mime = " + mime + "): " + baos.toString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
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 . ja v a 2 s .co m*/ 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:nl.b3p.viewer.image.ImageTool.java
/** Reads an image from an http input stream. * * @param method Apache HttpClient GetMethod object * @param mime String representing the mime type of the image. * * @return BufferedImage/*from w ww . j a va 2 s .c o m*/ * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(HttpMethod method, String mime) throws Exception { ImageReader ir = null; BufferedImage i = null; try { if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); /* TODO: Kijken waarom er geen mime type meer binnenkomt. Wellicht door de * HttpClient vernieuwing in kaartenbalie ? */ if (mimeType == null) { mimeType = "image/png"; } if (mimeType == null) { log.error("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); throw new Exception("Response from server not understood (mime = " + mime + "): " + method.getResponseBodyAsString()); } ir = getReader(mimeType); if (ir == null) { log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); throw new Exception("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1)); } //TODO Make smarter.. Possibly faster... But keep reporting! InputStream is = method.getResponseBodyAsStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0; byte[] buffer = new byte[2048]; while (bytesRead != -1) { bytesRead = is.read(buffer, 0, buffer.length); if (bytesRead > 0) { baos.write(buffer, 0, bytesRead); } } ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); i = ir.read(0); //if image is a png, has no alpha and has a tRNS then make that color transparent. if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) { PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0); if (metadata.tRNS_present) { int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue); BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB); for (int x = 0; x < i.getWidth(); x++) { for (int y = 0; y < i.getHeight(); y++) { int rgb = i.getRGB(x, y); rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb; tmp.setRGB(x, y, rgb); } } i = tmp; } } } finally { if (ir != null) { ir.dispose(); } } return i; }
From source file:lucee.runtime.img.Image.java
public IIOMetadata getMetaData(Struct parent) { InputStream is = null;//from w w w . java 2 s .c om javax.imageio.stream.ImageInputStreamImpl iis = null; try { if (source instanceof File) { iis = new FileImageInputStream((File) source); } else if (source == null) iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true))); else iis = new MemoryCacheImageInputStream(is = source.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { // pick the first available ImageReader ImageReader reader = readers.next(); IIOMetadata meta = null; synchronized (sync) { // attach source to the reader reader.setInput(iis, true); // read metadata of first image meta = reader.getImageMetadata(0); meta.setFromTree(FORMAT, meta.getAsTree(FORMAT)); reader.reset(); } // generating dump if (parent != null) { String[] formatNames = meta.getMetadataFormatNames(); for (int i = 0; i < formatNames.length; i++) { Node root = meta.getAsTree(formatNames[i]); //print.out(XMLCaster.toString(root)); addMetaddata(parent, "metadata", root); } } return meta; } } catch (Throwable t) { } finally { ImageUtil.closeEL(iis); IOUtil.closeEL(is); } return null; }