List of usage examples for javax.imageio.metadata IIOMetadataNode getElementsByTagName
public NodeList getElementsByTagName(String name)
From source file:com.aegon.pdf2tiff.TIFFUtil.java
/** * Updates the given ImageIO metadata with Sun's custom TIFF tags. * {@see https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/ * apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java} * {@see http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/ * plugins/tiff/package-summary.html} * {@see http://partners.adobe.com/public/developer/tiff/index.html} * @param image buffered image which will be written * @param metadata ImageIO metadata/*from www. j av a2 s.c o m*/ * @param dpi image dots per inch */ public static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) { debugLogMetadata(metadata, SUN_TIFF_FORMAT); if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) { LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName()); return; } IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT); IIOMetadataNode ifd; if (root.getElementsByTagName("TIFFIFD").getLength() == 0) { ifd = new IIOMetadataNode("TIFFIFD"); ifd.setAttribute("tagSets", "com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet"); root.appendChild(ifd); } else { ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0); } // standard metadata does not work, so we set the DPI manually ifd.appendChild(createRationalField(282, "XResolution", dpi, 1)); ifd.appendChild(createRationalField(283, "YResolution", dpi, 1)); ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight())); ifd.appendChild(createAsciiField(305, "Software", "PDFBOX")); if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { // set PhotometricInterpretation WhiteIsZero // because of bug in Windows XP preview ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0)); } try { metadata.mergeTree(SUN_TIFF_FORMAT, root); } catch (IIOInvalidTreeException e) { // should never happen throw new RuntimeException(e); } debugLogMetadata(metadata, SUN_TIFF_FORMAT); }
From source file:com.ackpdfbox.app.imageio.TIFFUtil.java
/** * Updates the given ImageIO metadata with Sun's custom TIFF tags, as described in * the <a href="https://svn.apache.org/repos/asf/xmlgraphics/commons/tags/commons-1_3_1/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOTIFFImageWriter.java">org.apache.xmlgraphics.image.writer.ImageIOTIFFImageWriter * sources</a>, /*from ww w.j ava 2 s. c o m*/ * the <a href="http://download.java.net/media/jai-imageio/javadoc/1.0_01/com/sun/media/imageio/plugins/tiff/package-summary.html">com.sun.media.imageio.plugins.tiff * package javadoc</a> * and the <a href="http://partners.adobe.com/public/developer/tiff/index.html">TIFF * specification</a>. * * @param image buffered image which will be written * @param metadata ImageIO metadata * @param dpi image dots per inch * @throws IIOInvalidTreeException if something goes wrong */ static void updateMetadata(IIOMetadata metadata, BufferedImage image, int dpi) throws IIOInvalidTreeException { debugLogMetadata(metadata, SUN_TIFF_FORMAT); if (!SUN_TIFF_FORMAT.equals(metadata.getNativeMetadataFormatName())) { LOG.debug("Using unknown TIFF image writer: " + metadata.getNativeMetadataFormatName()); return; } IIOMetadataNode root = new IIOMetadataNode(SUN_TIFF_FORMAT); IIOMetadataNode ifd; if (root.getElementsByTagName("TIFFIFD").getLength() == 0) { ifd = new IIOMetadataNode("TIFFIFD"); ifd.setAttribute("tagSets", tagSetClassName); root.appendChild(ifd); } else { ifd = (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0); } // standard metadata does not work, so we set the DPI manually ifd.appendChild(createRationalField(282, "XResolution", dpi, 1)); ifd.appendChild(createRationalField(283, "YResolution", dpi, 1)); ifd.appendChild(createShortField(296, "ResolutionUnit", 2)); // Inch ifd.appendChild(createLongField(278, "RowsPerStrip", image.getHeight())); ifd.appendChild(createAsciiField(305, "Software", "PDFBOX")); if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { // set PhotometricInterpretation WhiteIsZero // because of bug in Windows XP preview ifd.appendChild(createShortField(262, "PhotometricInterpretation", 0)); } metadata.mergeTree(SUN_TIFF_FORMAT, root); debugLogMetadata(metadata, SUN_TIFF_FORMAT); }
From source file:com.ackpdfbox.app.imageio.ImageIOUtil.java
/** * Gets the named child node, or creates and attaches it. * * @param parentNode the parent node/* w w w .j ava 2 s.c o m*/ * @param name name of the child node * * @return the existing or just created child node */ private static IIOMetadataNode getOrCreateChildNode(IIOMetadataNode parentNode, String name) { NodeList nodeList = parentNode.getElementsByTagName(name); if (nodeList != null && nodeList.getLength() > 0) { return (IIOMetadataNode) nodeList.item(0); } IIOMetadataNode childNode = new IIOMetadataNode(name); parentNode.appendChild(childNode); return childNode; }
From source file:com.sketchy.utils.image.SketchyImage.java
public static void save(SketchyImage sketchyImage, File file) throws Exception { if (!file.getParentFile().canWrite()) { throw new Exception("Can not write to File: " + file.getPath() + "!"); }// w w w. j av a2s .c o m if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not save SketchyImage! Must be a .png file!"); } Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName("png"); ImageWriter imageWriter = null; if (imageWriters.hasNext()) { // Just get first one imageWriter = imageWriters.next(); } if (imageWriter == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageOutputStream os = null; try { os = ImageIO.createImageOutputStream(file); imageWriter.setOutput(os); ImageWriteParam imageWriterParam = imageWriter.getDefaultWriteParam(); IIOMetadata metadata = imageWriter.getDefaultImageMetadata( ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_BYTE_BINARY), imageWriterParam); String metaDataFormatName = metadata.getNativeMetadataFormatName(); IIOMetadataNode metaDataNode = (IIOMetadataNode) metadata.getAsTree(metaDataFormatName); NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); IIOMetadataNode physNode = null; if (childNodes.getLength() == 0) { physNode = new IIOMetadataNode("pHYs"); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } else { for (int nodeIdx = 0; nodeIdx < childNodes.getLength(); nodeIdx++) { physNode = (IIOMetadataNode) childNodes.item(nodeIdx); physNode.setAttribute("pixelsPerUnitXAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterWidth * 1000))); physNode.setAttribute("pixelsPerUnitYAxis", Integer.toString((int) Math.ceil(sketchyImage.dotsPerMillimeterHeight * 1000))); physNode.setAttribute("unitSpecifier", "meter"); // always meter metaDataNode.appendChild(physNode); } } metadata.setFromTree(metaDataFormatName, metaDataNode); imageWriter.write(new IIOImage(sketchyImage.image, null, metadata)); os.flush(); } catch (Exception e) { throw new Exception("Error Saving SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(os); } }
From source file:net.rptools.tokentool.util.ImageUtil.java
private static ImageView getImage(ImageView thumbView, final Path filePath, final boolean overlayWanted, final int THUMB_SIZE) throws IOException { Image thumb = null;// ww w .ja v a 2s .c om String fileURL = filePath.toUri().toURL().toString(); if (ImageUtil.SUPPORTED_IMAGE_FILE_FILTER.accept(null, fileURL)) { if (THUMB_SIZE <= 0) thumb = processMagenta(new Image(fileURL), COLOR_THRESHOLD, overlayWanted); else thumb = processMagenta(new Image(fileURL, THUMB_SIZE, THUMB_SIZE, true, true), COLOR_THRESHOLD, overlayWanted); } else if (ImageUtil.PSD_FILE_FILTER.accept(null, fileURL)) { ImageInputStream is = null; PSDImageReader reader = null; int imageIndex = 1; // Mask layer should always be layer 1 and overlay image on layer 2. Note, layer 0 will be a combined layer composite if (overlayWanted) imageIndex = 2; File file = filePath.toFile(); try { is = ImageIO.createImageInputStream(file); if (is == null || is.length() == 0) { log.info("Image from file " + file.getAbsolutePath() + " is null"); } Iterator<ImageReader> iterator = ImageIO.getImageReaders(is); if (iterator == null || !iterator.hasNext()) { throw new IOException("Image file format not supported by ImageIO: " + filePath); } reader = (PSDImageReader) iterator.next(); reader.setInput(is); BufferedImage thumbBI; thumbBI = reader.read(imageIndex); if (thumbBI != null) { int layerIndex = 0; if (overlayWanted) layerIndex = 1; IIOMetadata metadata = reader.getImageMetadata(0); IIOMetadataNode root = (IIOMetadataNode) metadata .getAsTree(PSDMetadata.NATIVE_METADATA_FORMAT_NAME); NodeList layerInfos = root.getElementsByTagName("LayerInfo"); // Layer index corresponds to imageIndex - 1 in the reader IIOMetadataNode layerInfo = (IIOMetadataNode) layerInfos.item(layerIndex); // Get the width & height of the Mask layer so we can create the overlay the same size int width = reader.getWidth(0); int height = reader.getHeight(0); // Get layer offsets, PhotoShop PSD layers can have different widths/heights and all images start at 0,0 with a layer offset applied int x = Math.max(Integer.parseInt(layerInfo.getAttribute("left")), 0); int y = Math.max(Integer.parseInt(layerInfo.getAttribute("top")), 0); // Lets pad the overlay with transparency to make it the same size as the PSD canvas size thumb = resizeCanvas(SwingFXUtils.toFXImage(thumbBI, null), width, height, x, y); // Finally set ImageView to thumbnail size if (THUMB_SIZE > 0) { thumbView.setFitWidth(THUMB_SIZE); thumbView.setPreserveRatio(true); } } } catch (Exception e) { log.error("Processing: " + file.getAbsolutePath(), e); } finally { // Dispose reader in finally block to avoid memory leaks reader.dispose(); is.close(); } } thumbView.setImage(thumb); return thumbView; }
From source file:com.sketchy.utils.image.SketchyImage.java
public static SketchyImage load(File file) throws Exception { SketchyImage sketchyImage = null;/*from w w w. j ava 2 s.c om*/ if (!file.exists() || !file.canRead()) { throw new Exception("Can not find or read File: " + file.getPath() + "!"); } if (!StringUtils.endsWithIgnoreCase(file.getName(), ".png")) { throw new Exception("Can not load SketchyImage! Must be a .png file!"); } Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("png"); ImageReader imageReader = null; if (imageReaders.hasNext()) { // Just get first one imageReader = imageReaders.next(); } if (imageReader == null) { // this should never happen!! if so.. we got problems throw new Exception("Can not find ImageReader for .png Files!"); } ImageInputStream is = null; try { is = ImageIO.createImageInputStream(file); imageReader.setInput(is, true); IIOMetadata metaData = imageReader.getImageMetadata(0); // always get first image IIOMetadataNode metaDataNode = (IIOMetadataNode) metaData .getAsTree(metaData.getNativeMetadataFormatName()); if (metaDataNode == null) { throw new Exception("Error retreiving MetaData properties from .png File!"); } NodeList childNodes = metaDataNode.getElementsByTagName("pHYs"); // only look in the first node if (childNodes.getLength() == 0) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnit' MetaData!"); } IIOMetadataNode physNode = (IIOMetadataNode) childNodes.item(0); String pixelsPerUnitXAxisAttribute = physNode.getAttribute("pixelsPerUnitXAxis"); String pixelsPerUnitYAxisAttribute = physNode.getAttribute("pixelsPerUnitYAxis"); // String unitSpecifierAttribute = physNode.getAttribute("unitSpecifier"); Just assuming meter if (StringUtils.isBlank(pixelsPerUnitXAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitXAxis' MetaData!"); } if (StringUtils.isBlank(pixelsPerUnitYAxisAttribute)) { throw new Exception("Invalid SketchyImage file. It must contain 'pixelsPerUnitYAxis' MetaData!"); } int pixelsPerUnitXAxis; try { pixelsPerUnitXAxis = Integer.parseInt(pixelsPerUnitXAxisAttribute); if (pixelsPerUnitXAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitXAxis' MetaData Attribute! " + e.getMessage()); } int pixelsPerUnitYAxis; try { pixelsPerUnitYAxis = Integer.parseInt(pixelsPerUnitYAxisAttribute); if (pixelsPerUnitYAxis <= 0) throw new Exception("Value must be > 0"); } catch (Exception e) { throw new Exception("Invalid 'pixelsPerUnitYAxis' MetaData Attribute! " + e.getMessage()); } // We successfully processed the MetaData.. now read/set the image BufferedImage bufferedImage = imageReader.read(0); // always get first image double xPixelsPerMM = pixelsPerUnitXAxis / 1000.0; double yPixelsPerMM = pixelsPerUnitYAxis / 1000.0; sketchyImage = new SketchyImage(bufferedImage, xPixelsPerMM, yPixelsPerMM); } catch (Exception e) { throw new Exception("Error Loading SketchyImage File: " + file.getPath() + "! " + e.getMessage()); } finally { IOUtils.closeQuietly(is); } return sketchyImage; }
From source file:org.photovault.image.ImageIOImage.java
/** * Parse JPEG metadata structure and store the data in metadata and exifData fields * @param top The metadata object tree in format "javax_imageio_jpeg_image_1.0" *//* w w w .j av a2s .co m*/ private void parseJPEGMetadata(IIOMetadataNode top) { NodeList candidates = top.getElementsByTagName("unknown"); for (int n = 0; n < candidates.getLength(); n++) { Node node = candidates.item(n); if (node instanceof IIOMetadataNode) { IIOMetadataNode m = (IIOMetadataNode) node; Object obj = m.getUserObject(); if (obj instanceof byte[]) { byte[] data = (byte[]) obj; if (data[0] == 'E' && data[1] == 'x' && data[2] == 'i' && data[3] == 'f') { log.debug("exif data found"); InputStream is = new ByteArrayInputStream(data, 6, data.length - 6); try { ImageInputStream metadataStream = ImageIO.createImageInputStream(is); Iterator readers = ImageIO.getImageReadersByFormatName("TIFF"); if (readers.hasNext()) { ImageReader reader = (ImageReader) readers.next(); reader.setInput(metadataStream); IIOMetadata iioMetadata = reader.getImageMetadata(0); this.metadata = TIFFDirectory.createFromMetadata(iioMetadata); TIFFField exifField = this.metadata .getTIFFField(EXIFParentTIFFTagSet.TAG_EXIF_IFD_POINTER); } } catch (IOException ex) { ex.printStackTrace(); } } else if (data.length > 28 && data[28] == 0) { String id = null; try { id = new String(data, 0, 28, "utf-8"); } catch (UnsupportedEncodingException e) { log.error(e); } if ("http://ns.adobe.com/xap/1.0/".equals(id)) { // XMP metadata try { String xmpPacket = new String(data, 29, data.length - 29, "utf-8"); XMPMeta xmp = XMPMetaFactory.parseFromString(xmpPacket); log.debug("Found XMP metadata"); } catch (XMPException e) { log.warn("caught XMP exception while parsing metadata", e); } catch (UnsupportedEncodingException e) { log.error(e); } } } } } } }
From source file:org.photovault.imginfo.CreateCopyImageCommand.java
/** Helper function to save a rendered image to file @param instanceFile The file into which the image will be saved @param img Image that willb e saved/*from w w w. j av a2s .c o m*/ @param xmpData XPM metadata packet that should be saved with the image @throws PhotovaultException if saving does not succeed */ protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException { ImageOutputStream out = null; log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath()); try { out = new FileImageOutputStream(instanceFile); } catch (IOException e) { log.error("Error writing image: " + e.getMessage()); throw new PhotovaultException(e.getMessage()); } if (img.getSampleModel().getSampleSize(0) == 16) { log.debug("16 bit image, converting to 8 bits"); double[] subtract = new double[1]; subtract[0] = 0; double[] divide = new double[1]; divide[0] = 1. / 256.; // Now we can rescale the pixels gray levels: ParameterBlock pbRescale = new ParameterBlock(); pbRescale.add(divide); pbRescale.add(subtract); pbRescale.addSource(img); PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null); // Make sure it is a byte image - force conversion. ParameterBlock pbConvert = new ParameterBlock(); pbConvert.addSource(outputImage); pbConvert.add(DataBuffer.TYPE_BYTE); img = JAI.create("format", pbConvert); } IIOImage iioimg = new IIOImage(img, null, null); /* Not all encoders support metadata handling */ Iterator writers = ImageIO.getImageWritersByFormatName("jpeg"); ImageWriter imgwriter = null; while (writers.hasNext()) { imgwriter = (ImageWriter) writers.next(); if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) { // Break on finding the core provider. break; } } if (imgwriter == null) { System.err.println("Cannot find core JPEG writer!"); } imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() { public void warningOccurred(ImageWriter arg0, int arg1, String arg2) { log.warn("Warning from ImageWriter: " + arg2); } }); ImageWriteParam params = imgwriter.getDefaultWriteParam(); ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img); IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null); IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence"); if (markerSeqNodes.getLength() > 0) { IIOMetadataNode xmpNode = new IIOMetadataNode("unknown"); xmpNode.setAttribute("MarkerTag", "225"); xmpNode.setUserObject(xmpData); markerSeqNodes.item(0).appendChild(xmpNode); } try { metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop); } catch (Exception e) { log.warn("error editing metadata: " + e.getMessage()); e.printStackTrace(); throw new PhotovaultException("error setting image metadata: \n" + e.getMessage()); } iioimg.setMetadata(metadata); try { imgwriter.setOutput(out); imgwriter.write(iioimg); } catch (IOException e) { log.warn("Exception while encoding" + e.getMessage()); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } finally { try { out.close(); } catch (IOException e) { log.warn("Exception while closing file: " + e.getMessage()); imgwriter.dispose(); throw new PhotovaultException( "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage()); } imgwriter.dispose(); } log.debug("Exit: saveImage"); }