List of usage examples for javax.imageio ImageReader getImageMetadata
public abstract IIOMetadata getImageMetadata(int imageIndex) throws IOException;
From source file:it.tidalwave.imageio.example.stats.FocalLengthStats.java
public static void main(final String[] args) { try {/* w w w . j av a2 s . c om*/ final PrintWriter out = new PrintWriter(new File(args[1])); new DirectoryWalker() { @Override protected void handleFile(final File file, final int depth, final Collection results) throws IOException { if (file.getName().toUpperCase().endsWith(".NEF")) { System.out.printf("Processing %s...\n", file.getCanonicalPath()); final ImageReader reader = (ImageReader) ImageIO.getImageReaders(file).next(); reader.setInput(ImageIO.createImageInputStream(file)); final IIOMetadata metadata = reader.getImageMetadata(0); final NEFMetadata nefMetadata = (NEFMetadata) metadata; final IFD exifIFD = nefMetadata.getExifIFD(); final TagRational focalLength = exifIFD.getFocalLength(); out.println(focalLength.doubleValue()); } } public void start() throws IOException { super.walk(new File(args[0]), new ArrayList<Object>()); } }.start(); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.mpg.imeji.presentation.metadata.extractors.BasicExtractor.java
public static List<String> extractTechMd(Item item) throws Exception { List<String> techMd = new ArrayList<String>(); URI uri = item.getFullImageUrl(); String imageUrl = uri.toURL().toString(); GetMethod method = new GetMethod(imageUrl); method.setFollowRedirects(false);/* w w w. ja v a2s. c o m*/ String userHandle = null; userHandle = LoginHelper.login(PropertyReader.getProperty("imeji.escidoc.user"), PropertyReader.getProperty("imeji.escidoc.password")); method.addRequestHeader("Cookie", "escidocCookie=" + userHandle); HttpClient client = new HttpClient(); client.executeMethod(method); InputStream input = method.getResponseBodyAsStream(); ImageInputStream iis = ImageIO.createImageInputStream(input); 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++) { displayMetadata(techMd, metadata.getAsTree(names[i])); } } return techMd; }
From source file:com.sketchy.utils.image.SketchyImage.java
public static SketchyImage load(File file) throws Exception { SketchyImage sketchyImage = null;/* w w w.j a va2 s.co m*/ 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:nl.b3p.kaartenbalie.service.KBImageTool.java
/** Reads an image from an http input stream. * * @param is Inputstream// w w w . j a v a 2 s. c om * @param mime String representing the mime type of the image. * * @return BufferedImage * * @throws Exception */ // <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method."> public static BufferedImage readImage(InputStream is, String mime, ServiceProviderRequest wmsRequest) 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); } if (mime.indexOf(";") != -1) { mime = mime.substring(0, mime.indexOf(";")); } String mimeType = getMimeType(mime); if (mimeType == null) { String message = baos.toString(); message = message.replaceAll("(\\r|\\n)", ""); log.error("Response from server not understood (mime = " + mime + "): " + message); throw new Exception("Response from server not understood (mime = " + mime + "): " + message); } ImageReader 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! wmsRequest.setBytesReceived(new Long(baos.size())); ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray())); ir.setInput(stream, true); try { //if image is a png, has no alpha and has a tRNS then make that color transparent. BufferedImage i = ir.read(0); 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; } } return i; } finally { ir.dispose(); } }
From source file:net.algart.simagis.imageio.IIOMetadataToJsonConverter.java
private JSONObject extendedReadExif(InputStream inputStream) throws IOException, JSONException { assert inputStream != null; ImageInputStream iis = ImageIO.createImageInputStream(inputStream); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); try {//from w w w . j a v a 2s . c o m if (!readers.hasNext()) { return null; // no readers to read such "Exif" } ImageReader reader = readers.next(); try { reader.setInput(iis); return toJson(reader.getImageMetadata(0)); } finally { reader.dispose(); } } finally { iis.close(); } }
From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java
/** * checks whether the compression of a TIFF file is as expected. * * @param filename Filename/* w w w . j a v a 2s . co m*/ * @param expectedCompression expected TIFF compression * * @throws IOException if something goes wrong */ void checkTiffCompression(String filename, String expectedCompression) throws IOException { Iterator readers = ImageIO.getImageReadersBySuffix("tiff"); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new File(filename)); reader.setInput(iis); IIOMetadata imageMetadata = reader.getImageMetadata(0); Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT); Element comprElement = (Element) root.getElementsByTagName("Compression").item(0); Node comprTypeNode = comprElement.getElementsByTagName("CompressionTypeName").item(0); String actualCompression = comprTypeNode.getAttributes().getNamedItem("value").getNodeValue(); assertEquals("Incorrect TIFF compression in file " + filename, expectedCompression, actualCompression); iis.close(); reader.dispose(); }
From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java
/** * checks whether the resolution of an image file is as expected. * * @param filename the name of the file/*from w ww . j a v a2s. co m*/ * @param expectedResolution the expected resolution * * @throws IOException if something goes wrong */ private void checkResolution(String filename, int expectedResolution) throws IOException { assertFalse("Empty file " + filename, new File(filename).length() == 0); String suffix = filename.substring(filename.lastIndexOf('.') + 1); if ("BMP".equals(suffix.toUpperCase())) { // BMP reader doesn't work checkBmpResolution(filename, expectedResolution); return; } Iterator readers = ImageIO.getImageReadersBySuffix(suffix); assertTrue("No image reader found for suffix " + suffix, readers.hasNext()); ImageReader reader = (ImageReader) readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new File(filename)); assertNotNull("No ImageInputStream created for file " + filename, iis); reader.setInput(iis); IIOMetadata imageMetadata = reader.getImageMetadata(0); Element root = (Element) imageMetadata.getAsTree(STANDARD_METADATA_FORMAT); NodeList dimensionNodes = root.getElementsByTagName("Dimension"); assertTrue("No resolution found in image file " + filename, dimensionNodes.getLength() > 0); Element dimensionElement = (Element) dimensionNodes.item(0); NodeList pixelSizeNodes = dimensionElement.getElementsByTagName("HorizontalPixelSize"); assertTrue("No X resolution found in image file " + filename, pixelSizeNodes.getLength() > 0); Node pixelSizeNode = pixelSizeNodes.item(0); String val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue(); int actualResolution = (int) Math.round(25.4 / Double.parseDouble(val)); assertEquals("X resolution doesn't match in image file " + filename, expectedResolution, actualResolution); pixelSizeNodes = dimensionElement.getElementsByTagName("VerticalPixelSize"); assertTrue("No Y resolution found in image file " + filename, pixelSizeNodes.getLength() > 0); pixelSizeNode = pixelSizeNodes.item(0); val = pixelSizeNode.getAttributes().getNamedItem("value").getNodeValue(); actualResolution = (int) Math.round(25.4 / Double.parseDouble(val)); assertEquals("Y resolution doesn't match", expectedResolution, actualResolution); iis.close(); reader.dispose(); }
From source file:com.qwazr.extractor.parser.ImageParser.java
@Override public void parseContent(final MultivaluedMap<String, String> parameters, final Path path, final String extension, final String mimeType, final ParserResultBuilder resultBuilder) throws Exception { final ImagePHash imgPhash = new ImagePHash(); try (final ImageInputStream in = ImageIO.createImageInputStream(path.toFile())) { final Iterator<ImageReader> readers = ImageIO.getImageReaders(in); if (readers.hasNext()) { ParserFieldsBuilder result = resultBuilder.newDocument(); ImageReader reader = readers.next(); resultBuilder.metas().set(MIME_TYPE, "image/" + reader.getFormatName().toLowerCase()); try { reader.setInput(in);//from www . j a v a 2 s.c om result.add(WIDTH, reader.getWidth(0)); result.add(HEIGHT, reader.getHeight(0)); result.add(FORMAT, reader.getFormatName()); result.add(PHASH, imgPhash.getHash(reader.read(0))); IIOMetadata metadata = reader.getImageMetadata(0); if (metadata != null) { String[] names = metadata.getMetadataFormatNames(); if (names != null) for (String name : names) browseNodes("META", metadata.getAsTree(name), result); } } finally { reader.dispose(); } } } }
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" *///from ww w. jav a2 s. c o 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.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(); }// www . j av a2 s . co 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(); }