Java Code Examples for javax.imageio.ImageIO.getImageReaders()

The following are Jave code examples for showing how to use getImageReaders() of the javax.imageio.ImageIO class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openjdk-jdk10   File: JpegMetadataColorSpaceTest.java   View Source Code Vote up 8 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 2
Project: fwm   File: AddableImage.java   View Source Code Vote up 6 votes
public File addImageExtension(File incoming) throws IOException {
	
	String format = null;
	ImageInputStream iis = ImageIO.createImageInputStream(incoming);
	Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
	while (imageReaders.hasNext()) {
	    ImageReader reader = (ImageReader) imageReaders.next();
	    format = reader.getFormatName().toLowerCase();
	    log.debug("filetype is: " + format);

	    File newfile = new File("imageimage." + format);
		if (newfile.exists()) {
			newfile.delete();    	
		}
		
	    Files.copy(incoming.toPath(), newfile.toPath());
	    incoming.delete();

	    return newfile;
	}
	return null;
	
}
 
Example 3
Project: projectindoorweb   File: TransformationHelper.java   View Source Code Vote up 6 votes
/**
 * Extracts the picture size of a given Image.
 *
 * @param path Path to the image
 * @return Image-size in pixel
 * @throws IOException Throws exception when file-access fails
 */
public static Dimension getPictureSize(final String path) throws IOException {
    try (ImageInputStream in = ImageIO.createImageInputStream(path)) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
        if (readers.hasNext()) {
            ImageReader reader = readers.next();
            try {
                reader.setInput(in);
                return new Dimension(reader.getWidth(0), reader.getHeight(0));
            } finally {
                reader.dispose();
            }
        }
        return null;
    }
}
 
Example 4
Project: VASSAL-src   File: ImageIOImageLoader.java   View Source Code Vote up 6 votes
/**
 * Gets the size of an image.
 *
 * @param name the image name
 * @param in the input stream
 * @return the size of the image
 *
 * @throws BrokenImageException if the image is faulty
 * @throws UnrecognizedImageTypeException if the image type is unknown
 * @throws IOException if reading the image goes wrong
 */
public Dimension run(String name, InputStream in) throws IOException {
  final ImageInputStream stream = new MemoryCacheImageInputStream(in);

  final Iterator<ImageReader> i = ImageIO.getImageReaders(stream);
  if (!i.hasNext()) throw new UnrecognizedImageTypeException(name);

  final ImageReader reader = i.next();
  try {
    reader.setInput(stream);
    return new Dimension(reader.getWidth(0), reader.getHeight(0));
  }
  finally {
    reader.dispose();
  }
}
 
Example 5
Project: openjdk-jdk10   File: JpegRawImageTypeTest.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {

        //nomarkers.jpg has YCbCr color space
        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 imageFile = new File(filePath);

        ImageInputStream inputStream = ImageIO.
            createImageInputStream(imageFile);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(inputStream);

        if(readers.hasNext()) {
            ImageReader reader = readers.next();
            reader.setInput(inputStream);

            ImageTypeSpecifier typeSpecifier = reader.getRawImageType(0);
            //check if ImageTypeSpecifier is null for YCbCr JPEG Image
            if (typeSpecifier == null) {
                throw new RuntimeException("ImageReader returns null raw image"
                    + " type");
            }
        }
    }
 
Example 6
Project: syndesis   File: ConnectorsITCase.java   View Source Code Vote up 5 votes
@Test
public void testUpdateIcon() throws IOException {
    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("icon", new InputStreamResource(getClass().getResourceAsStream("test-image.png")));

    final ResponseEntity<Connector> updated = post("/api/v1/connectors/twitter/icon",
        multipartData, Connector.class, tokenRule.validToken(), HttpStatus.OK,
        multipartHeaders());

    assertThat(updated.getBody().getId()).isPresent();
    assertThat(updated.getBody().getIcon()).isNotBlank().startsWith("db:");

    final ResponseEntity<ByteArrayResource> got = get("/api/v1/connectors/twitter/icon", ByteArrayResource.class);
    assertThat(got.getHeaders().getFirst("Content-Type")).isEqualTo("image/png");

    try (ImageInputStream iis = ImageIO.createImageInputStream(got.getBody().getInputStream());) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            final ImageReader reader = readers.next();
            try {
                reader.setInput(iis);
                final Dimension dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0));
                assertThat(dimensions.getHeight()).isEqualTo(106d).as("Wrong image height");
                assertThat(dimensions.getWidth()).isEqualTo(106d).as("Wrong image width");
            } finally {
                reader.dispose();
            }
        }
    }
}
 
Example 7
Project: raven   File: ImageUtils.java   View Source Code Vote up 5 votes
private static String getImageFormatName(final byte[] imageBytes)
		throws IOException {
	ByteArrayInputStream input = new ByteArrayInputStream(imageBytes);
	ImageInputStream imageInput = ImageIO.createImageInputStream(input);
	Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInput);
	String imageFormatName = null;
	if (iterator.hasNext()) {
		ImageReader reader = iterator.next();
		imageFormatName = reader.getFormatName().toUpperCase();
	}

	try {
		return imageFormatName;
	} finally {
		if (imageInput != null) {
			imageInput.close();
		}
	}
}
 
Example 8
Project: openjdk-jdk10   File: ImageIOGetImageReaders.java   View Source Code Vote up 5 votes
public static void main(String[] args) {
    boolean gotIAE = false;
    try {
        ImageIO.getImageReaders(null);
    } catch (IllegalArgumentException e) {
        gotIAE = true;
    }

    if (!gotIAE) {
        throw new RuntimeException("Failed to get IAE!");
    }
}
 
Example 9
Project: marathonv5   File: ImagePanel.java   View Source Code Vote up 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();
    }
}
 
Example 10
Project: syndesis   File: ConnectorHandlerTest.java   View Source Code Vote up 4 votes
@Test
public void connectorIconShouldHaveCorrectContentType() throws IOException {
    try (MockWebServer mockWebServer = new MockWebServer(); final Buffer resultBuffer = new Buffer()) {
        mockWebServer.start();

        resultBuffer.writeAll(Okio.source(getClass().getResourceAsStream("test-image.png")));

        mockWebServer.enqueue(new MockResponse().setHeader(CONTENT_TYPE, "image/png").setBody(resultBuffer));

        final Connector connector = new Connector.Builder().id("connector-id").icon(mockWebServer.url("/u/23079786").toString())
            .build();
        when(dataManager.fetch(Connector.class, "connector-id")).thenReturn(connector);
        when(dataManager.fetchAll(Integration.class)).thenReturn(ListResult.of(Collections.emptyList()));

        final Response response = handler.getConnectorIcon("connector-id").get();

        assertThat(response.getStatusInfo()).isEqualTo(Response.Status.OK).as("Wrong status code");
        assertThat(response.getHeaderString(CONTENT_TYPE)).isEqualTo("image/png").as("Wrong content type");
        assertThat(response.getHeaderString(CONTENT_LENGTH)).isEqualTo("2018").as("Wrong content length");

        final StreamingOutput so = (StreamingOutput) response.getEntity();
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (BufferedSink sink = Okio.buffer(Okio.sink(bos)); BufferedSource source = new Buffer();
            ImageInputStream iis = ImageIO.createImageInputStream(source.inputStream());) {
            so.write(sink.outputStream());
            source.readAll(sink);
            final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
            if (readers.hasNext()) {
                final ImageReader reader = readers.next();
                try {
                    reader.setInput(iis);
                    final Dimension dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0));
                    assertThat(dimensions.getHeight()).isEqualTo(106d).as("Wrong image height");
                    assertThat(dimensions.getWidth()).isEqualTo(106d).as("Wrong image width");
                } finally {
                    reader.dispose();
                }
            }
        }
    }
}
 
Example 11
Project: syndesis   File: ConnectorsITCase.java   View Source Code Vote up 4 votes
@Test
public void testUpdateConnectorAndIconViaMultipart() throws IOException {
    final Connector initialConnector = dataManager.fetch(Connector.class, "twitter");

    assertThat(initialConnector.getIcon()).isNotBlank().doesNotStartWith("db:");

    final Connector connectorWithNewdescription = new Connector.Builder().createFrom(initialConnector)
        .description("Updated!").build();

    final LinkedMultiValueMap<String, Object> multipartData = new LinkedMultiValueMap<>();
    multipartData.add("connector", connectorWithNewdescription);
    multipartData.add("icon", new InputStreamResource(getClass().getResourceAsStream("test-image.png")));

    final ResponseEntity<Void> updated = put("/api/v1/connectors/twitter",
        multipartData, Void.class, tokenRule.validToken(), HttpStatus.NO_CONTENT,
        multipartHeaders());

    final ResponseEntity<Connector> updatedConnector = get("/api/v1/connectors/twitter", Connector.class);

    assertThat(updatedConnector.getBody().getId()).isPresent();
    assertThat(updatedConnector.getBody().getIcon()).isNotBlank().startsWith("db:");
    assertThat(updatedConnector.getBody().getDescription()).isNotBlank().isEqualTo("Updated!");

    final ResponseEntity<ByteArrayResource> got = get("/api/v1/connectors/twitter/icon", ByteArrayResource.class);
    assertThat(got.getHeaders().getFirst("Content-Type")).isEqualTo("image/png");

    try (ImageInputStream iis = ImageIO.createImageInputStream(got.getBody().getInputStream());) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            final ImageReader reader = readers.next();
            try {
                reader.setInput(iis);
                final Dimension dimensions = new Dimension(reader.getWidth(0), reader.getHeight(0));
                assertThat(dimensions.getHeight()).isEqualTo(106d).as("Wrong image height");
                assertThat(dimensions.getWidth()).isEqualTo(106d).as("Wrong image width");
            } finally {
                reader.dispose();
            }
        }
    }
}
 
Example 12
Project: Yass   File: YassUtils.java   View Source Code Vote up 4 votes
/**
 * Description of the Method
 *
 * @param source Description of the Parameter
 * @return Description of the Return Value
 * @throws IOException Description of the Exception
 */
public static BufferedImage readImage(Object source) throws IOException {
    ImageInputStream stream = ImageIO.createImageInputStream(source);
    if (stream == null) {
        if (source instanceof java.net.URL) {
            return ImageIO.read((java.net.URL) source);
        } else {
            return null;
        }
    }
    Iterator<?> it = ImageIO.getImageReaders(stream);
    if (!it.hasNext()) {
        // bug with firefox 2
        BufferedImage buf = null;
        if (source instanceof File) {
            buf = ImageIO.read((File) source);
        }
        return buf;
    }
    ImageReader reader = (ImageReader) it.next();
    reader.setInput(stream);
    ImageReadParam param = reader.getDefaultReadParam();

    ImageTypeSpecifier typeToUse = null;
    boolean looking = true;
    for (Iterator<?> i = reader.getImageTypes(0); i.hasNext() && looking; ) {
        ImageTypeSpecifier type = (ImageTypeSpecifier) i.next();
        if (type.getColorModel().getColorSpace().getNumComponents() == 1) {
            typeToUse = type;
            looking = false;
        } else if (type.getColorModel().getColorSpace().isCS_sRGB()) {
            typeToUse = type;
            looking = false;
        }
    }
    if (typeToUse != null) {
        param.setDestinationType(typeToUse);
    }

    BufferedImage b = null;
    try {
        b = reader.read(0, param);
    } catch (Exception e) {
        e.printStackTrace();
    }

    reader.dispose();
    stream.close();
    return b;
}
 
Example 13
Project: openjdk-jdk10   File: ReadAbortTest.java   View Source Code Vote up 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 14
Project: openjdk-jdk10   File: BMPPixelSpacingTest.java   View Source Code Vote up 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 15
Project: CustomWorldGen   File: SplashProgress.java   View Source Code Vote up 4 votes
public Texture(ResourceLocation location, boolean allowRP)
{
    InputStream s = null;
    try
    {
        this.location = location;
        s = open(location, allowRP);
        ImageInputStream stream = ImageIO.createImageInputStream(s);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
        if(!readers.hasNext()) throw new IOException("No suitable reader found for image" + location);
        ImageReader reader = readers.next();
        reader.setInput(stream);
        frames = reader.getNumImages(true);
        BufferedImage[] images = new BufferedImage[frames];
        for(int i = 0; i < frames; i++)
        {
            images[i] = reader.read(i);
        }
        reader.dispose();
        int size = 1;
        width = images[0].getWidth();
        height = images[0].getHeight();
        while((size / width) * (size / height) < frames) size *= 2;
        this.size = size;
        glEnable(GL_TEXTURE_2D);
        synchronized(SplashProgress.class)
        {
            name = glGenTextures();
            glBindTexture(GL_TEXTURE_2D, name);
        }
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size, size, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (IntBuffer)null);
        checkGLError("Texture creation");
        for(int i = 0; i * (size / width) < frames; i++)
        {
            for(int j = 0; i * (size / width) + j < frames && j < size / width; j++)
            {
                buf.clear();
                BufferedImage image = images[i * (size / width) + j];
                for(int k = 0; k < height; k++)
                {
                    for(int l = 0; l < width; l++)
                    {
                        buf.put(image.getRGB(l, k));
                    }
                }
                buf.position(0).limit(width * height);
                glTexSubImage2D(GL_TEXTURE_2D, 0, j * width, i * height, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, buf);
                checkGLError("Texture uploading");
            }
        }
        glBindTexture(GL_TEXTURE_2D, 0);
        glDisable(GL_TEXTURE_2D);
    }
    catch(IOException e)
    {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    finally
    {
        IOUtils.closeQuietly(s);
    }
}