List of usage examples for javax.imageio ImageReader dispose
public void dispose()
From source file:org.exoplatform.wcm.ext.component.activity.FileUIActivity.java
protected int getImageHeight(Node node) { int imageHeight = 0; try {//from w w w. j a v a 2s . co m if (node.hasNode(NodetypeConstant.JCR_CONTENT)) node = node.getNode(NodetypeConstant.JCR_CONTENT); ImageReader reader = ImageIO.getImageReadersByMIMEType(mimeType).next(); ImageInputStream iis = ImageIO.createImageInputStream(node.getProperty("jcr:data").getStream()); reader.setInput(iis, true); imageHeight = reader.getHeight(0); iis.close(); reader.dispose(); } catch (Exception e) { LOG.info("Cannot get node"); } return imageHeight; }
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 w w w. ja va2 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.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(); }// w w w .jav a 2 s . c o 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(); }
From source file:org.apache.pdfbox.tools.imageio.TestImageIOUtils.java
/** * checks whether the compression of a TIFF file is as expected. * * @param filename Filename/*from w w w . j a v a2 s .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:nl.b3p.kaartenbalie.service.KBImageTool.java
/** Reads an image from an http input stream. * * @param is Inputstream//from w w w . j ava 2s . c o m * @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:jails.http.converter.BufferedImageHttpMessageConverter.java
public BufferedImage read(Class<? extends BufferedImage> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { ImageInputStream imageInputStream = null; ImageReader imageReader = null; try {/*from w w w . j a va2 s .c o m*/ imageInputStream = createImageInputStream(inputMessage.getBody()); MediaType contentType = inputMessage.getHeaders().getContentType(); Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString()); if (imageReaders.hasNext()) { imageReader = imageReaders.next(); ImageReadParam irp = imageReader.getDefaultReadParam(); process(irp); imageReader.setInput(imageInputStream, true); return imageReader.read(0, irp); } else { throw new HttpMessageNotReadableException( "Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]"); } } finally { if (imageReader != null) { imageReader.dispose(); } if (imageInputStream != null) { try { imageInputStream.close(); } catch (IOException ex) { // ignore } } } }
From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java
private static SizeAndBufferedImage getImage(ImageInputStream stream, String suffix) { Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix); if (iter.hasNext()) { ImageReader reader = iter.next(); try {/*from w w w. ja v a 2 s . c o m*/ reader.setInput(stream, true, true); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); Size size = new Size(width, height, false); SizeAndBufferedImage all = new SizeAndBufferedImage(size, null); int readerMinIndex = reader.getMinIndex(); ImageReadParam param = reader.getDefaultReadParam(); Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0); while (imageTypes.hasNext()) { try { ImageTypeSpecifier imageTypeSpecifier = imageTypes.next(); int bufferedImageType = imageTypeSpecifier.getBufferedImageType(); if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) { param.setDestinationType(imageTypeSpecifier); } all.setImage(reader.read(readerMinIndex, param)); return all; } catch (IllegalArgumentException e) { log.warn(e.getMessage(), e); } } } catch (IOException e) { log.error(e.getMessage(), e); } finally { reader.dispose(); } } else { log.error("No reader found for given format: " + suffix, null); } return null; }
From source file:uk.bl.wa.analyser.payload.ImageAnalyser.java
@Override public void analyse(String source, ArchiveRecordHeader header, InputStream tikainput, SolrRecord solr) { // Set up metadata object to pass to parsers: Metadata metadata = new Metadata(); // Skip large images: if (header.getLength() > max_size_bytes) { return;// ww w. java 2s .c om } // Only attempt to analyse a random sub-set of the data: // (prefixing with static test of a final value to allow JIT to fully // optimise out the "OR Math.random()" bit) if (sampleRate >= 1.0 || Math.random() < sampleRate) { // Increment number of images sampled: sampleCount++; // images are enabled, we still want to extract image/height (fast) //This method takes 0.2ms for a large image. I can be done even faster if needed(but more complicated)). //see https://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java ImageInputStream input = null; ImageReader reader = null; try { input = ImageIO.createImageInputStream(tikainput); reader = ImageIO.getImageReaders(input).next(); reader.setInput(input); // Get dimensions of first image in the stream, without decoding pixel values int width = reader.getWidth(0); int height = reader.getHeight(0); // Store basic image data: solr.addField(SolrFields.IMAGE_HEIGHT, "" + height); solr.addField(SolrFields.IMAGE_WIDTH, "" + width); solr.addField(SolrFields.IMAGE_SIZE, "" + (height * width)); } catch (Exception e) { //it is known that (most) .ico and (all) .svg are not supported by java. Do not log, since it will spam. // log.warn("Unable to extract image height/width/size for url:"+header.getUrl(),e); } finally { if (reader != null) { reader.dispose(); } } } }
From source file:org.jimcat.services.imagemanager.ImageUtil.java
/** * use this methode to load an image from a given byte array * /* w w w.ja va 2 s . c o m*/ * @param data - * the byte array containing an encoded image * @param quality * the rendering quality * @return - a Buffered Image containing image. Its size is limited by * SOURCE_BOUNDING_BOX constant * @throws IOException - * if something goes wrong */ public static BufferedImage loadImage(byte[] data, ImageQuality quality) throws IOException { // read first element ImageReader reader = getReaderForImage(data); // get image dimension and calculate resulting image size int width = reader.getWidth(0); int height = reader.getHeight(0); Dimension size = getScaledDimension(width, height, SOURCE_BOUNDING_BOX, false); // performe read BufferedImage bi = null; try { if (USE_TILES) { // if image is smaller than a tile if (width <= IMAGE_TILE_SIZE.width && height <= IMAGE_TILE_SIZE.height) { bi = reader.read(0); } else { // prepaire reader ImageReadParam param = reader.getDefaultReadParam(); // so image is bigger than a tile // a) check if reader supports source scaling if (param.canSetSourceRenderSize()) { // fine => do it so param.setSourceRenderSize(size); bi = reader.read(0, param); } else { // so, scaling has to be done by hand bi = loadImageWithTiles(reader, size, quality); } } } else { bi = loadImageWithSubSampling(reader, size, quality); } } finally { reader.dispose(); } return bi; }
From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java
/** * prepares render process and gets IView2 file and combines tiles. * The image dimensions and path are determined from {@link HttpServletRequest#getPathInfo()}: * <code>/{zoomAlias}/{derivateID}/{absoluteImagePath}</code> * where <code>zoomAlias</code> is mapped like this: * <table>// w w w . j ava 2s . c o m * <caption>Mapping of zoomAlias to actual zoom level</caption> * <tr><th>zoomAlias</th><th>zoom level</th></tr> * <tr><td>'MIN'</td><td>1</td></tr> * <tr><td>'MID'</td><td>2</td></tr> * <tr><td>'MAX'</td><td>3</td></tr> * <tr><td>default and all others</td><td>0</td></tr> * </table> * * See {@link #init()} how to attach a footer to every generated image. */ @Override protected void think(final MCRServletJob job) throws IOException, JDOMException { final HttpServletRequest request = job.getRequest(); try { String pathInfo = request.getPathInfo(); if (pathInfo.startsWith("/")) { pathInfo = pathInfo.substring(1); } String zoomAlias = pathInfo.substring(0, pathInfo.indexOf('/')); pathInfo = pathInfo.substring(zoomAlias.length() + 1); final String derivate = pathInfo.substring(0, pathInfo.indexOf('/')); String imagePath = pathInfo.substring(derivate.length()); LOGGER.info("Zoom-Level: " + zoomAlias + ", derivate: " + derivate + ", image: " + imagePath); final Path iviewFile = MCRImage.getTiledFile(MCRIView2Tools.getTileDir(), derivate, imagePath); try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) { Path iviewFileRoot = fs.getRootDirectories().iterator().next(); final MCRTiledPictureProps pictureProps = MCRTiledPictureProps .getInstanceFromDirectory(iviewFileRoot); final int maxZoomLevel = pictureProps.getZoomlevel(); request.setAttribute(THUMBNAIL_KEY, iviewFile); LOGGER.info("IView2 file: " + iviewFile); int zoomLevel = 0; switch (zoomAlias) { case "MIN": zoomLevel = 1; break; case "MID": zoomLevel = 2; break; case "MAX": zoomLevel = 3; break; } HttpServletResponse response = job.getResponse(); if (zoomLevel > maxZoomLevel) { switch (maxZoomLevel) { case 2: zoomAlias = "MID"; break; case 1: zoomAlias = "MIN"; break; default: zoomAlias = "THUMB"; break; } if (!imagePath.startsWith("/")) imagePath = "/" + imagePath; String redirectURL = response.encodeRedirectURL(MessageFormat.format("{0}{1}/{2}/{3}{4}", request.getContextPath(), request.getServletPath(), zoomAlias, derivate, imagePath)); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); response.setHeader("Location", redirectURL); response.flushBuffer(); return; } if (zoomLevel == 0 && footerImpl == null) { //we're done, sendThumbnail is called in render phase return; } ImageReader reader = MCRIView2Tools.getTileImageReader(); try { BufferedImage combinedImage = MCRIView2Tools.getZoomLevel(iviewFileRoot, pictureProps, reader, zoomLevel); if (combinedImage != null) { if (footerImpl != null) { BufferedImage footer = footerImpl.getFooter(combinedImage.getWidth(), derivate, imagePath); combinedImage = attachFooter(combinedImage, footer); } request.setAttribute(IMAGE_KEY, combinedImage); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } finally { reader.dispose(); } } } finally { LOGGER.info("Finished sending " + request.getPathInfo()); } }