List of usage examples for javax.imageio.metadata IIOMetadata setFromTree
public void setFromTree(String formatName, Node root) throws IIOInvalidTreeException
From source file:eu.europa.esig.dss.pades.signature.visible.ImageFactory.java
private static void initDpi(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException { Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(dpi)); jfif.setAttribute("Ydensity", Integer.toString(dpi)); jfif.setAttribute("resUnits", "1"); // density is dots per inch metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree); }
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 a v a2 s . co 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.d53dev.dslfy.web.service.GifService.java
private void configureGIFFrame(IIOMetadata meta, String delayTime, int imageIndex, String disposalMethod, int loopCount) { String metaFormat = meta.getNativeMetadataFormatName(); if (!"javax_imageio_gif_image_1.0".equals(metaFormat)) { throw new IllegalArgumentException("Unfamiliar gif metadata format: " + metaFormat); }//from w w w . j a v a2 s. c o m Node root = meta.getAsTree(metaFormat); Node child = root.getFirstChild(); while (child != null) { if ("GraphicControlExtension".equals(child.getNodeName())) break; child = child.getNextSibling(); } IIOMetadataNode gce = (IIOMetadataNode) child; gce.setAttribute("userDelay", "FALSE"); gce.setAttribute("delayTime", delayTime); gce.setAttribute("disposalMethod", disposalMethod); if (imageIndex == 0) { IIOMetadataNode aes = new IIOMetadataNode("ApplicationExtensions"); IIOMetadataNode ae = new IIOMetadataNode("ApplicationExtension"); ae.setAttribute("applicationID", "NETSCAPE"); ae.setAttribute("authenticationCode", "2.0"); byte[] uo = new byte[] { 0x1, (byte) (loopCount & 0xFF), (byte) ((loopCount >> 8) & 0xFF) }; ae.setUserObject(uo); aes.appendChild(ae); root.appendChild(aes); } try { meta.setFromTree(metaFormat, root); } catch (IIOInvalidTreeException e) { throw new Error(e); } }
From source file:lucee.runtime.img.Image.java
public IIOMetadata getMetaData(Struct parent) { InputStream is = null;/*from w w w .j av a2s. 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; }
From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java
/************************************************************************************ * set metadata to image/*from w ww . j a v a2 s. co m*/ * * @param iomd the given {@link IIOMetadata} to set ************************************************************************************/ private void setMetadata(IIOMetadata iomd) { Node node = iomd.getAsTree("javax_imageio_jpeg_image_1.0"); // set dimensions setSamplesPerLine(node, this.getWidth()); setNumLines(node, this.getHeight()); // what are child nodes? NodeList nl = node.getChildNodes(); for (int j = 0; j < nl.getLength(); j++) { Node n = nl.item(j); if (n.getNodeName().equals("JPEGvariety")) { NodeList childNodes = n.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { if (childNodes.item(k).getNodeName().equals("app0JFIF")) { // get the attributes resUnits, Xdensity, and Ydensity Node resUnitsNode = getAttributeByName(childNodes.item(k), "resUnits"); Node XdensityNode = getAttributeByName(childNodes.item(k), "Xdensity"); Node YdensityNode = getAttributeByName(childNodes.item(k), "Ydensity"); // overwrite values for that node resUnitsNode.setNodeValue("1"); // it's dpi int xres = (int) this.getXResolution(); int yres = (int) this.getYResolution(); if (xres == 0) { xres = defaultXResolution; } if (yres == 0) { yres = defaultYResolution; } XdensityNode.setNodeValue(String.valueOf(xres)); YdensityNode.setNodeValue(String.valueOf(yres)); } // endif } // end id break; // don't need to change the other children } // end id } // end for // set the XML tree for the IIOMetadata object try { iomd.setFromTree("javax_imageio_jpeg_image_1.0", node); } catch (IIOInvalidTreeException e) { LOGGER.error(e); // To change body of catch statement } }
From source file:nl.softwaredesign.exporter.ODTExportFormat.java
/** * TODO Move to utility class?/*from ww w . j av a2 s. co m*/ * Extract the content data (bytes) from the given image. * @param icon image to get bytes for * @param format desired format for image * @param background Color to use as background if transparency in image * @param width Desired width of the image in the byte array * @param height Desired width of the image in the byte array * @return the bytes of the image * @throws IOException */ private byte[] imageToBytes(ImageIcon icon, String format, Color background, int width, int height) throws IOException { Iterator writers = ImageIO.getImageWritersByFormatName(format); ImageWriter writer = (ImageWriter) writers.next(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(output); writer.setOutput(ios); BufferedImage img; if ("png".equalsIgnoreCase(format) || "gif".equalsIgnoreCase(format)) { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } WaitingObserver observer = new WaitingObserver(); if (!img.getGraphics().drawImage(icon.getImage(), 0, 0, width, height, background, observer)) { try { observer.waitForDone(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new byte[0]; } } IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(img), writer.getDefaultWriteParam()); if (format.equalsIgnoreCase("jpg")) { Element tree = (Element) metadata.getAsTree("javax_imageio_jpeg_image_1.0"); Element jfif = (Element) tree.getElementsByTagName("app0JFIF").item(0); jfif.setAttribute("Xdensity", Integer.toString(72)); jfif.setAttribute("Ydensity", Integer.toString(72)); jfif.setAttribute("resUnits", "1"); metadata.setFromTree("javax_imageio_jpeg_image_1.0", tree); } else { double dotsPerMilli = 7.2 / 2.54; IIOMetadataNode horiz = new IIOMetadataNode("HorizontalPixelSize"); horiz.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode vert = new IIOMetadataNode("VerticalPixelSize"); vert.setAttribute("value", Double.toString(dotsPerMilli)); IIOMetadataNode dim = new IIOMetadataNode("Dimension"); dim.appendChild(horiz); dim.appendChild(vert); IIOMetadataNode root = new IIOMetadataNode("javax_imageio_1.0"); root.appendChild(dim); metadata.mergeTree("javax_imageio_1.0", root); } writer.write(null, new IIOImage(img, null, metadata), null); return output.toByteArray(); }
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 a2 s.co 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"); }