Java Code Examples for javax.imageio.ImageIO#getImageReaders()
The following examples show how to use
javax.imageio.ImageIO#getImageReaders() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtil.java From density-converter with Apache License 2.0 | 6 votes |
@Deprecated public static BufferedImage readSvg(File file, Dimension sourceDimension) throws Exception { try (ImageInputStream input = ImageIO.createImageInputStream(file)) { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (!readers.hasNext()) { throw new IllegalArgumentException("No reader for: " + file); } ImageReader reader = readers.next(); try { reader.setInput(input); ImageReadParam param = reader.getDefaultReadParam(); param.setSourceRenderSize(sourceDimension); return reader.read(0, param); } finally { reader.dispose(); } } }
Example 2
Source File: ImageReaders.java From JglTF with MIT License | 6 votes |
/** * Tries to find an <code>ImageReader</code> that is capable of reading * the given image data. The returned image reader will be initialized * by passing an ImageInputStream that is created from the given data * to its <code>setInput</code> method. The caller is responsible for * disposing the returned image reader. * * @param imageData The image data * @return The image reader * @throws IOException If no matching image reader can be found */ @SuppressWarnings("resource") public static ImageReader findImageReader(ByteBuffer imageData) throws IOException { InputStream inputStream = Buffers.createByteBufferInputStream(imageData.slice()); ImageInputStream imageInputStream = ImageIO.createImageInputStream(inputStream); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream); if (imageReaders.hasNext()) { ImageReader imageReader = imageReaders.next(); imageReader.setInput(imageInputStream); return imageReader; } throw new IOException("Could not find ImageReader for image data"); }
Example 3
Source File: ImageFileReaders.java From MyBox with Apache License 2.0 | 6 votes |
public static IIOMetadata getIIOMetadata(File file) { try { try ( ImageInputStream iis = ImageIO.createImageInputStream(file)) { Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis, false); IIOMetadata iioMetaData = reader.getImageMetadata(0); reader.dispose(); return iioMetaData; } } return null; } catch (Exception e) { logger.error(e.toString()); return null; } }
Example 4
Source File: ImageLoadTwelveMonkeysTest.java From java-image-processing-survival-guide with Apache License 2.0 | 6 votes |
/** * Load a multi-page TIFF image and split it into its individual pages. */ @Test public void testExtractPagesFromMultiPageTiffCompression4() throws Exception { File sourceImageFile = getImageFile("tiff", "test-multi-gray-compression-type-4.tiff"); ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile); // get the first matching reader Iterator<ImageReader> iterator = ImageIO.getImageReaders(is); ImageReader imageReader = iterator.next(); imageReader.setInput(is); // split the multi-page TIFF int pages = imageReader.getNumImages(true); for (int i = 0; i < pages; i++) { BufferedImage bufferedImage = imageReader.read(i); assertValidBufferedImage(bufferedImage); } assertEquals("Expect to have 2 pages", 2, pages); }
Example 5
Source File: SimpleSelectionIIIFBuilder.java From wandora with GNU General Public License v3.0 | 6 votes |
public static int[] getImageDimensions(Object f) throws IOException { if(f instanceof URL) f=((URL)f).openStream(); ImageInputStream in = ImageIO.createImageInputStream(f); try{ final Iterator readers = ImageIO.getImageReaders(in); if(readers.hasNext()){ ImageReader reader=(ImageReader)readers.next(); try{ reader.setInput(in); return new int[]{reader.getWidth(0), reader.getHeight(0)}; }finally{ reader.dispose(); } } }finally { if(in!=null) in.close(); } return null; }
Example 6
Source File: JpegMetadataColorSpaceTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws IOException { String fileName = "nomarkers.jpg"; String sep = System.getProperty("file.separator"); String dir = System.getProperty("test.src", "."); String filePath = dir+sep+fileName; System.out.println("Test file: " + filePath); File file = new File(filePath); ImageInputStream stream = ImageIO.createImageInputStream(file); Iterator<ImageReader> readers = ImageIO.getImageReaders(stream); if(readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(stream); IIOMetadata metadata = reader.getImageMetadata(0); IIOMetadataNode standardTree = (IIOMetadataNode) metadata.getAsTree (IIOMetadataFormatImpl.standardMetadataFormatName); IIOMetadataNode colorSpaceType = (IIOMetadataNode) standardTree.getElementsByTagName("ColorSpaceType").item(0); String colorSpaceName = colorSpaceType.getAttribute("name"); if(colorSpaceName.equals("RGB")) throw new RuntimeException("Identified incorrect ColorSpace"); } }
Example 7
Source File: ImageUtil.java From java-sdk with Apache License 2.0 | 6 votes |
public static String getImageFormat(ImageInputStream input) { Iterator<ImageReader> readers = ImageIO.getImageReaders(input); String format = "unknown"; if (readers.hasNext()) { ImageReader reader = readers.next(); try { format = reader.getFormatName(); } catch (IOException e) { e.printStackTrace(); } finally { reader.dispose(); } } return format; }
Example 8
Source File: ImageUtils.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
/** * WARNING: WILL CLOSE YOUR STREAM!!! * * Check image format. Use this instead of checking format by file name. * * @param stream {@link InputStream} File input stream * @return true if validation pass, false in other case */ public static boolean isValidImage(InputStream stream) { if (stream == null) { throw new IllegalArgumentException("File stream could not be empty."); } try (ImageInputStream iis = ImageIO.createImageInputStream(stream)) { Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis); if (iterator.hasNext()) { ImageReader reader = iterator.next(); return isValidImageFileExtension(reader.getFormatName()); } } catch (IOException e) { // Do nothing } return false; }
Example 9
Source File: ImageLoadJaiTest.java From java-image-processing-survival-guide with Apache License 2.0 | 6 votes |
/** * Load a multi-page TIFF image and split it into its individual pages. */ @Test public void testExtractPagesFromMultiPageTiffCompression4() throws Exception { File sourceImageFile = getImageFile("tiff", "test-multi-gray-compression-type-4.tiff"); ImageInputStream is = ImageIO.createImageInputStream(sourceImageFile); // get the first matching reader Iterator<ImageReader> iterator = ImageIO.getImageReaders(is); ImageReader imageReader = iterator.next(); imageReader.setInput(is); // split the multi-page TIFF int pages = imageReader.getNumImages(true); for (int i = 0; i < pages; i++) { BufferedImage bufferedImage = imageReader.read(i); assertValidBufferedImage(bufferedImage); } assertEquals("Expect to have 2 pages", 2, pages); }
Example 10
Source File: HtmlTagBasedGenerator.java From fess with Apache License 2.0 | 5 votes |
protected Result saveImage(final ImageInputStream input, final File outputFile) throws IOException { final FessConfig fessConfig = ComponentUtil.getFessConfig(); final Iterator<ImageReader> readers = ImageIO.getImageReaders(input); if (readers.hasNext()) { final ImageReader reader = readers.next(); try { reader.setInput(input); final ImageReadParam param = reader.getDefaultReadParam(); final int width = reader.getWidth(0); final int height = reader.getHeight(0); if (width <= 0 || height <= 0) { return Result.NO_IMAGE; } if (!fessConfig.validateThumbnailSize(width, height)) { return Result.INVALID_SIZE; } final int samplingWidth = width / fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger(); final int samplingHeight = height / fessConfig.getThumbnailHtmlImageThumbnailHeightAsInteger(); param.setSourceSubsampling(samplingWidth <= 0 ? 1 : samplingWidth, samplingHeight <= 0 ? 1 : samplingHeight, 0, 0); param.setSourceRegion(new Rectangle(width, height > width ? width : height)); final BufferedImage image = reader.read(0, param); final int thumbnailWidth = fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger(); final int thumbnailHeight = (int) ((height > width ? width : height) * fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger().floatValue() / width); final BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, image.getType()); thumbnail.getGraphics().drawImage(image.getScaledInstance(thumbnailWidth, thumbnailHeight, Image.SCALE_AREA_AVERAGING), 0, 0, thumbnailWidth, thumbnailHeight, null); ImageIO.write(thumbnail, fessConfig.getThumbnailHtmlImageFormat(), outputFile); image.flush(); return Result.OK; } finally { reader.dispose(); } } return Result.FAILED; }
Example 11
Source File: BigBufferedImage.java From OpenRS with GNU General Public License v3.0 | 5 votes |
public static BufferedImage create(File inputFile, int imageType) throws IOException { try (ImageInputStream stream = ImageIO.createImageInputStream(inputFile);) { Iterator<ImageReader> readers = ImageIO.getImageReaders(stream); if (readers.hasNext()) { try { ImageReader reader = readers.next(); reader.setInput(stream, true, true); int width = reader.getWidth(reader.getMinIndex()); int height = reader.getHeight(reader.getMinIndex()); BufferedImage image = create(width, height, imageType); int cores = Math.max(1, Runtime.getRuntime().availableProcessors() / 2); int block = Math.min(MAX_PIXELS_IN_MEMORY / cores / width, (int) (Math.ceil(height / (double) cores))); ExecutorService generalExecutor = Executors.newFixedThreadPool(cores); List<Callable<ImagePartLoader>> partLoaders = new ArrayList<>(); for (int y = 0; y < height; y += block) { partLoaders.add(new ImagePartLoader( y, width, Math.min(block, height - y), inputFile, image)); } generalExecutor.invokeAll(partLoaders); generalExecutor.shutdown(); return image; } catch (InterruptedException ex) { Logger.getLogger(BigBufferedImage.class.getName()).log(Level.SEVERE, null, ex); } } } return null; }
Example 12
Source File: Images.java From jease with GNU General Public License v3.0 | 5 votes |
/** * Returns format name for given image. */ public static String getFormat(File image) throws IOException { ImageInputStream stream = ImageIO .createImageInputStream(new FileInputStream(image)); Iterator<ImageReader> iter = ImageIO.getImageReaders(stream); if (!iter.hasNext()) { return null; } ImageReader reader = (ImageReader) iter.next(); stream.close(); return reader.getFormatName(); }
Example 13
Source File: MainPanel.java From java-swing-tips with MIT License | 5 votes |
private static List<BufferedImage> loadFromStream(ImageInputStream imageStream) throws IOException { Iterable<ImageReader> it = () -> ImageIO.getImageReaders(imageStream); ImageReader reader = StreamSupport.stream(it.spliterator(), false) .filter(MainPanel::checkGifFormat) .findFirst() .orElseThrow(() -> new IOException("Can not read image format!")); reader.setInput(imageStream, false, false); List<BufferedImage> list = new ArrayList<>(); for (int i = 0; i < reader.getNumImages(true); i++) { IIOImage frame = reader.readAll(i, null); list.add((BufferedImage) frame.getRenderedImage()); } reader.dispose(); return list; }
Example 14
Source File: ImageUtils.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
private static ImageReader getImageReader(ImageInputStream iis) { Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); ImageReader reader = getRasterReader(readers); if (reader == null) { throw new DSSException("No reader for the image found"); } return reader; }
Example 15
Source File: ImageUtils.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
private static Image rescale(Image image, int width, int height) throws InvalidImageException { try { ImageInputStream imageInputStream = ImageIO.createImageInputStream(image.getData()); Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream); while (imageReaders.hasNext()) { ImageReader reader = imageReaders.next(); String discoveredType = reader.getFormatName(); if (! ALLOWED_MIMETYPE.contains(discoveredType)) { throw new InvalidImageException(discoveredType + " format is not supported"); } reader.setInput(imageInputStream); reader.getNumImages(true); BufferedImage bufferedImage = reader.read(0); java.awt.Image scaledImage = bufferedImage.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH); BufferedImage bufferedScaledImage = new BufferedImage(width, height, bufferedImage.getType()); Graphics2D g2 = bufferedScaledImage.createGraphics(); g2.drawImage(scaledImage, 0, 0, null); g2.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufferedScaledImage, discoveredType, bos); return new Image(image.getType(), image.getMimeType(), bos.toByteArray()); } throw new InvalidImageException("Image can not be rescaled"); } catch (IOException ioe) { throw new InvalidImageException("Image can not be rescaled", ioe); } }
Example 16
Source File: Images.java From basic-tools with MIT License | 5 votes |
public static String getImageType(byte[] mapObj) throws IOException { String type = ""; try (ByteArrayInputStream bais = new ByteArrayInputStream(mapObj); MemoryCacheImageInputStream mcis = new MemoryCacheImageInputStream(bais)) { Iterator<ImageReader> itr = ImageIO.getImageReaders(mcis); while (itr.hasNext()) { ImageReader reader = itr.next(); String imageName = reader.getClass().getSimpleName(); if (imageName != null) { if ("GIFImageReader".equals(imageName)) { type = "gif"; } else if ("JPEGImageReader".equals(imageName)) { type = "jpg"; } else if ("PNGImageReader".equals(imageName)) { type = "png"; } else if ("BMPImageReader".equals(imageName)) { type = "bmp"; } else { type = "noPic"; } } } } catch (Exception e) { type = "noPic"; } return type; }
Example 17
Source File: ReadAbortTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public ReadAbortTest(String format) throws Exception { try { System.out.println("Test for format " + format); bimg = new BufferedImage(width, heght, BufferedImage.TYPE_INT_RGB); Graphics2D g = bimg.createGraphics(); g.setColor(srccolor); g.fillRect(0, 0, width, heght); g.dispose(); file = File.createTempFile("src_", "." + format, new File(".")); ImageIO.write(bimg, format, file); ImageInputStream iis = ImageIO.createImageInputStream(file); Iterator iter = ImageIO.getImageReaders(iis); while (iter.hasNext()) { reader = (ImageReader) iter.next(); break; } reader.setInput(iis); reader.addIIOReadProgressListener(this); // Abort reading in IIOReadProgressListener.imageStarted(). startAbort = true; bimg = reader.read(0); startAbort = false; // Abort reading in IIOReadProgressListener.imageProgress(). progressAbort = true; bimg = reader.read(0); progressAbort = false; iis.close(); /* * All abort requests from imageStarted,imageProgress and * imageComplete from IIOReadProgressListener should be reached * otherwise throw RuntimeException. */ if (!(startAborted && progressAborted)) { throw new RuntimeException("All IIOReadProgressListener abort" + " requests are not processed for format " + format); } } catch (Exception e) { throw e; } finally { Files.delete(file.toPath()); } }
Example 18
Source File: BMPPixelSpacingTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { // Header contaning X & Y pixels-per-meter more than value 1 byte[] bmpHeaderData = { (byte) 0x42, (byte) 0x4d, (byte) 0x7e, (byte) 0x06, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x3e, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x28, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x64, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff }; ImageInputStream imageInput = ImageIO. createImageInputStream(new ByteArrayInputStream(bmpHeaderData)); for (Iterator<ImageReader> it = ImageIO.getImageReaders(imageInput); it.hasNext(); ) { ImageReader reader = it.next(); reader.setInput(imageInput); IIOMetadata metadata = reader.getImageMetadata(0); Node rootNode = metadata.getAsTree("javax_imageio_1.0"); NodeList nl = rootNode.getChildNodes(); //Parse until you get Dimension child node for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if ((node.getNodeName()).equals("Dimension")) { //get childnode list under Dimension node NodeList cl = node.getChildNodes(); //Corresponding node indices under Dimension node int horizontalNodeIndex = 1; int verticalNodeIndex = 2; Node horizontalNode = cl.item(horizontalNodeIndex); Node verticalNode = cl.item(verticalNodeIndex); //get attributes for horizontal and vertical nodes NamedNodeMap horizontalAttr = horizontalNode. getAttributes(); NamedNodeMap verticalAttr = verticalNode.getAttributes(); //since they have only one attribute index is 0 int attributeIndex = 0; Node horizontalValue = horizontalAttr.item(attributeIndex); Node verticalValue = verticalAttr.item(attributeIndex); float horizontalNodeValue = Float. parseFloat((horizontalValue.getNodeValue())); float verticalNodeValue = Float. parseFloat((verticalValue.getNodeValue())); float expectedHorizontalValue, expectedVerticalValue; // in test metadata xPixelsPerMeter & yPixelsPerMeter is 2 expectedHorizontalValue = expectedVerticalValue = 1000.0F / 2; //expected and returned values should be same if ((Float.compare(horizontalNodeValue, expectedHorizontalValue) != 0) || (Float.compare(verticalNodeValue, expectedVerticalValue) != 0)) { throw new RuntimeException("Invalid pixel spacing"); } } } } }
Example 19
Source File: UIUtil.java From birt with Eclipse Public License 1.0 | 4 votes |
/** * Returns the DPI info of given image if applicable. * * @param imageStream * @return the DPI values in format of {hdpi, vdpi}. */ public static int[] getImageResolution( InputStream imageStream ) { int[] dpi = { 0, 0 }; if ( imageStream != null ) { try { ImageInputStream iis = ImageIO.createImageInputStream( imageStream ); Iterator<ImageReader> i = ImageIO.getImageReaders( iis ); ImageReader r = i.next( ); r.setInput( iis ); r.read( 0 ); IIOMetadata meta = r.getImageMetadata( 0 ); if ( meta != null ) { double mm2inch = 25.4; NodeList lst; Element node = (Element) meta.getAsTree( "javax_imageio_1.0" ); //$NON-NLS-1$ lst = node.getElementsByTagName( "HorizontalPixelSize" ); //$NON-NLS-1$ if ( lst != null && lst.getLength( ) == 1 ) { dpi[0] = (int) ( mm2inch / Float.parseFloat( ( (Element) lst.item( 0 ) ).getAttribute( "value" ) ) ); //$NON-NLS-1$ } lst = node.getElementsByTagName( "VerticalPixelSize" ); //$NON-NLS-1$ if ( lst != null && lst.getLength( ) == 1 ) { dpi[1] = (int) ( mm2inch / Float.parseFloat( ( (Element) lst.item( 0 ) ).getAttribute( "value" ) ) ); //$NON-NLS-1$ } } } catch ( Exception e ) { e.printStackTrace( ); } } return dpi; }
Example 20
Source File: ImagePanel.java From marathonv5 with Apache License 2.0 | 4 votes |
private void initializeAnnotations() { try { ImageInputStream iis = ImageIO.createImageInputStream(imageFile); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis); IIOMetadata imageMetadata = reader.getImageMetadata(0); org.w3c.dom.Node root = imageMetadata.getAsTree(imageMetadata.getNativeMetadataFormatName()); NodeList childNodes = root.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { org.w3c.dom.Node item = childNodes.item(i); if (item.getNodeName().equals("tEXt")) { org.w3c.dom.Node textNode = item; NodeList entryNodes = textNode.getChildNodes(); for (int j = 0; j < entryNodes.getLength(); j++) { org.w3c.dom.Node entry = entryNodes.item(j); if (entry.getNodeName().equals("tEXtEntry")) { NamedNodeMap attributes = entry.getAttributes(); String kw = attributes.getNamedItem("keyword").getNodeValue(); String value = attributes.getNamedItem("value").getNodeValue(); Pattern p = Pattern.compile("a1810-(\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)-(\\d+\\.\\d+)"); Matcher matcher = p.matcher(kw); if (matcher.matches()) { Annotation annotation = new Annotation(); annotation.setX(Double.parseDouble(matcher.group(2))); annotation.setY(Double.parseDouble(matcher.group(3))); annotation.setWidth(Double.parseDouble(matcher.group(4))); annotation.setHeight(Double.parseDouble(matcher.group(5))); annotation.setText(value); annotation.setFill(ANNOTATION_COLOR); annotations.add(annotation); } } } } } reader.dispose(); } } catch (IOException e) { e.printStackTrace(); } }