/** * Updates the metadata information based on the parameters to this writer. * * @param meta the metadata * @param params the parameters * @return the updated metadata */ protected IIOMetadata updateMetadata(IIOMetadata meta, ImageWriterParams params) { final String stdmeta = "javax_imageio_1.0"; if (meta.isStandardMetadataFormatSupported()) { IIOMetadataNode root = (IIOMetadataNode) meta.getAsTree(stdmeta); IIOMetadataNode dim = getChildNode(root, "Dimension"); IIOMetadataNode child; if (params.getResolution() != null) { child = getChildNode(dim, "HorizontalPixelSize"); if (child == null) { child = new IIOMetadataNode("HorizontalPixelSize"); dim.appendChild(child); } child.setAttribute("value", Double.toString(params.getResolution().doubleValue() / 25.4)); child = getChildNode(dim, "VerticalPixelSize"); if (child == null) { child = new IIOMetadataNode("VerticalPixelSize"); dim.appendChild(child); } child.setAttribute("value", Double.toString(params.getResolution().doubleValue() / 25.4)); } try { meta.mergeTree(stdmeta, root); } catch (IIOInvalidTreeException e) { throw new RuntimeException("Cannot update image metadata: " + e.getMessage()); } } return meta; }
/** * Reads image meta data. * * @param oimage * @return */ public static Map<String, String> readImageData(IIOImage oimage) { Map<String, String> dict = new HashMap<String, String>(); IIOMetadata imageMetadata = oimage.getMetadata(); if (imageMetadata != null) { IIOMetadataNode dimNode = (IIOMetadataNode) imageMetadata.getAsTree("javax_imageio_1.0"); NodeList nodes = dimNode.getElementsByTagName("HorizontalPixelSize"); int dpiX; if (nodes.getLength() > 0) { float dpcWidth = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue()); dpiX = (int) Math.round(25.4f / dpcWidth); } else { dpiX = Toolkit.getDefaultToolkit().getScreenResolution(); } dict.put("dpiX", String.valueOf(dpiX)); nodes = dimNode.getElementsByTagName("VerticalPixelSize"); int dpiY; if (nodes.getLength() > 0) { float dpcHeight = Float.parseFloat(nodes.item(0).getAttributes().item(0).getNodeValue()); dpiY = (int) Math.round(25.4f / dpcHeight); } else { dpiY = Toolkit.getDefaultToolkit().getScreenResolution(); } dict.put("dpiY", String.valueOf(dpiY)); } return dict; }
void readAndDisplayMetadata(String fileName) { try { File file = new File(fileName); 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); String[] names = metadata.getMetadataFormatNames(); int length = names.length; for (int i = 0; i < length; i++) { System.out.println("Format name: " + names[i]); displayMetadata(metadata.getAsTree(names[i])); } } } catch (Exception e) { e.printStackTrace(); } }
/** * Merges <code>inData</code> into <code>outData</code>. The supplied metadata format name is * attempted first and failing that the standard metadata format name is attempted. */ private void convertMetadata(String metadataFormatName, IIOMetadata inData, IIOMetadata outData) { String formatName = null; String nativeFormatName = inData.getNativeMetadataFormatName(); if (nativeFormatName != null && nativeFormatName.equals(metadataFormatName)) { formatName = metadataFormatName; } else { String[] extraFormatNames = inData.getExtraMetadataFormatNames(); if (extraFormatNames != null) { for (int i = 0; i < extraFormatNames.length; i++) { if (extraFormatNames[i].equals(metadataFormatName)) { formatName = metadataFormatName; break; } } } } if (formatName == null && inData.isStandardMetadataFormatSupported()) { formatName = STANDARD_METADATA_NAME; } if (formatName != null) { try { Node root = inData.getAsTree(formatName); outData.mergeTree(formatName, root); } catch (IIOInvalidTreeException e) { // ignore } } }
@Test public void metaDataTest() throws IOException { Iterator<ImageReader> itrR = ImageIO.getImageReadersByFormatName("jpg"); ImageReader imageReader = itrR.next(); ImageInputStream imageInputStream = ImageIO.createImageInputStream(new File(SRCIMG)); imageReader.setInput(imageInputStream, true); IIOMetadata ioMetadata = imageReader.getImageMetadata(0); System.out.println(ioMetadata.toString()); }
/** * Initialize a Map of attributes available from the underlying ImageMetadata. * * @param reader */ private void buildAttributesMap(SpatioTemporalImageReader reader) { attributesMap = new HashMap<String, String>(); IIOMetadata metadata; final int imageIndex = getImageIndex(); try { metadata = reader.getImageMetadata(imageIndex); if (metadata instanceof GRIB1ImageMetadata) { Node root = metadata.getAsTree(GRIB1ImageMetadata.nativeMetadataFormatName); if (root != null) { Node gdsNode = root.getFirstChild(); if (gdsNode != null) { final NamedNodeMap attributes = gdsNode.getAttributes(); if (attributes != null) { final int numAttributes = attributes.getLength(); for (int i = 0; i < numAttributes; i++) { final Node node = attributes.item(i); if (node != null) { attributesMap.put(node.getNodeName(), node.getNodeValue()); } } } } final Node pdsNode = gdsNode.getNextSibling(); if (pdsNode != null) { final NamedNodeMap attributes = pdsNode.getAttributes(); if (attributes != null) { final int numAttributes = attributes.getLength(); for (int i = 0; i < numAttributes; i++) { Node node = attributes.item(i); if (node != null) { attributesMap.put(node.getNodeName(), node.getNodeValue()); } } } } final Node pdsLevelNode = pdsNode.getNextSibling(); if (pdsLevelNode != null) { final NamedNodeMap attributes = pdsLevelNode.getAttributes(); if (attributes != null) { final int numAttributes = attributes.getLength(); for (int i = 0; i < numAttributes; i++) { Node node = attributes.item(i); if (node != null) { attributesMap.put(node.getNodeName(), node.getNodeValue()); } } } } } } } catch (IOException e) { throw new IllegalArgumentException("Unable parsing metadata"); } }
private static byte[] convertChartToByteArray( Chart chartDetails, JFreeChart chart, int width, int height) throws IOException, IIOInvalidTreeException { BufferedImage buffImg = chart.createBufferedImage( width, height, BufferedImage.BITMASK | BufferedImage.SCALE_SMOOTH, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next(); ImageWriteParam writeParam = writer.getDefaultWriteParam(); ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB); IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam); if (chartDetails != null) { if (chartDetails.getId() == null) { chartDetails.setId("%ID%"); } IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry"); textEntry.setAttribute("keyword", "chart-google-data"); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(bout); objectOutputStream.writeObject(chartDetails); objectOutputStream.flush(); textEntry.setAttribute( "value", (String) ChartRendererFactory.getRendererForOutput(ChartRendererGoogleTools.TYPE) .renderChart(chartDetails)); IIOMetadataNode text = new IIOMetadataNode("tEXt"); text.appendChild(textEntry); IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0"); root.appendChild(text); metadata.mergeTree("javax_imageio_png_1.0", root); } // setDPI(metadata); final ImageOutputStream stream = ImageIO.createImageOutputStream(baos); try { writer.setOutput(stream); writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam); } finally { stream.close(); } byte[] bytes = baos.toByteArray(); // ChartUtilities.encodeAsPNG(buffImg, true, 9); return bytes; }
/** * Set dpi in a JPEG file * * @param metadata the meta data * @param dpi the dpi * @throws IIOInvalidTreeException if something goes wrong */ static void updateMetadata(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException { debugLogMetadata(metadata, JPEG_NATIVE_FORMAT); // https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java // http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html Element root = (Element) metadata.getAsTree(JPEG_NATIVE_FORMAT); NodeList jvarNodeList = root.getElementsByTagName("JPEGvariety"); Element jvarChild; if (jvarNodeList.getLength() == 0) { jvarChild = new IIOMetadataNode("JPEGvariety"); root.appendChild(jvarChild); } else { jvarChild = (Element) jvarNodeList.item(0); } NodeList jfifNodeList = jvarChild.getElementsByTagName("app0JFIF"); Element jfifChild; if (jfifNodeList.getLength() == 0) { jfifChild = new IIOMetadataNode("app0JFIF"); jvarChild.appendChild(jfifChild); } else { jfifChild = (Element) jfifNodeList.item(0); } if (jfifChild.getAttribute("majorVersion").length() == 0) { jfifChild.setAttribute("majorVersion", "1"); } if (jfifChild.getAttribute("minorVersion").length() == 0) { jfifChild.setAttribute("minorVersion", "2"); } jfifChild.setAttribute("resUnits", "1"); // inch jfifChild.setAttribute("Xdensity", Integer.toString(dpi)); jfifChild.setAttribute("Ydensity", Integer.toString(dpi)); if (jfifChild.getAttribute("thumbWidth").length() == 0) { jfifChild.setAttribute("thumbWidth", "0"); } if (jfifChild.getAttribute("thumbHeight").length() == 0) { jfifChild.setAttribute("thumbHeight", "0"); } metadata.setFromTree(JPEG_NATIVE_FORMAT, root); // mergeTree doesn't work for ARGB }
@SuppressWarnings("unused") private boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file) { BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster wr = bufferedImage.getRaster(); wr.setPixels(0, 0, width, height, byteArray); try { // Image writer JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next(); ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file)); imageWriter.setOutput(ios); // Compression JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam(); jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT); jpegParams.setCompressionQuality(0.85f); // Metadata (dpi) IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams); Element tree = (Element) data.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 // Write and clean up imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams); ios.close(); imageWriter.dispose(); } catch (Exception e) { return false; } return true; }
@SuppressWarnings("unused") private static void setDPI(IIOMetadata metadata) throws IIOInvalidTreeException { // for PNG, it's dots per millimeter double dotsPerMilli = 1.0 * 600 / 10 / 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); }
private void writeHeader(IIOMetadata streamMetadata, int bitsPerPixel) throws IOException { GIFWritableStreamMetadata sm; if (streamMetadata instanceof GIFWritableStreamMetadata) { sm = (GIFWritableStreamMetadata) streamMetadata; } else { sm = new GIFWritableStreamMetadata(); Node root = streamMetadata.getAsTree(STREAM_METADATA_NAME); sm.setFromTree(STREAM_METADATA_NAME, root); } writeHeader( sm.version, sm.logicalScreenWidth, sm.logicalScreenHeight, sm.colorResolution, sm.pixelAspectRatio, sm.backgroundColorIndex, sm.sortFlag, bitsPerPixel, sm.globalColorTable); }