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

The following are Jave code examples for showing how to use createImageInputStream() 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: openjdk-jdk10   File: PngOutputTypeTest.java   View Source Code Vote up 6 votes
private static ImageInputStream createTestImage(int type) throws IOException  {
    int w = 100;
    int h = 100;

    BufferedImage img = new BufferedImage(w, h, type);

    int dx = w / colors.length;

    for (int i = 0; i < colors.length; i++) {
        for (int x = i *dx; (x < (i + 1) * dx) && (x < w) ; x++) {
            for (int y = 0; y < h; y++) {
                img.setRGB(x, y, colors[i].getRGB());
            }
        }
    }

    File pwd = new File(".");
    File out = File.createTempFile("rgba_", ".png", pwd);
    System.out.println("Create file: " + out.getAbsolutePath());
    ImageIO.write(img, "PNG", out);
    return ImageIO.createImageInputStream(out);
}
 
Example 3
Project: sucok-framework   File: ImageSizeUtils.java   View Source Code Vote up 6 votes
public static BufferedImage cut(String format, InputStream src, int x, int y, int w, int h) throws IOException {
	Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(format);
	ImageReader reader = (ImageReader) iterator.next();
	ImageInputStream iis = ImageIO.createImageInputStream(src);
	reader.setInput(iis, true);
	ImageReadParam param = reader.getDefaultReadParam();
	int imgWidth = reader.getWidth(0);
	int imgHeight = reader.getHeight(0);
	if (x + w > imgWidth) {
		w = imgWidth - x;
	}
	if (y + h > imgHeight) {
		h = imgHeight - y;
	}
	Rectangle rect = new Rectangle(x, y, w, h);
	param.setSourceRegion(rect);
	BufferedImage bi = reader.read(0, param);
	return bi;
}
 
Example 4
Project: openjdk-jdk10   File: EmbeddedFormatTest.java   View Source Code Vote up 6 votes
public void doTest(String compression, int bi_type) throws IOException {
    System.out.println("Test " + compression + " on " + getImageTypeName(bi_type));
    BufferedImage src = createTestImage(bi_type);
    writer.reset();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream ios =
            ImageIO.createImageOutputStream(baos);
    writer.setOutput(ios);

    ImageWriteParam wparam = prepareWriteParam(compression);
    writer.write(null, new IIOImage(src, null, null), wparam);
    ios.flush();
    ios.close();

    // read result
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    reader.reset();
    reader.setInput(iis);

    BufferedImage dst = reader.read(0);

    checkResult(dst);
}
 
Example 5
Project: openjdk-jdk10   File: CanDecodeTest.java   View Source Code Vote up 6 votes
public void doTest(ImageReaderSpi spi) throws IOException {
    System.out.println("Test for " + title +
            (canDecode ? " (can decode)" : " (can't decode)"));
    System.out.print("As a stream...");
    ImageInputStream iis =
            ImageIO.createImageInputStream(getDataStream());

    if (spi.canDecodeInput(iis) != canDecode) {
        throw new RuntimeException("Test failed: wrong decideion " +
                "for stream data");
    }
    System.out.println("OK");

    System.out.print("As a file...");
    iis = ImageIO.createImageInputStream(getDataFile());
    if (spi.canDecodeInput(iis) != canDecode) {
        throw new RuntimeException("Test failed: wrong decideion " +
                "for file data");
    }
    System.out.println("OK");
}
 
Example 6
Project: imageio-jnr   File: OpenJp2ImageReaderSpi.java   View Source Code Vote up 6 votes
@Override
public boolean canDecodeInput(Object input) throws IOException {
  if (!(input instanceof ImageInputStream)) {
    input = ImageIO.createImageInputStream(input);
  }
  if (input == null) {
    return false;
  }
  ImageInputStream stream = (ImageInputStream)input;
  byte[] b = new byte[12];
  try {
    stream.mark();
    stream.readFully(b);
  } catch (IOException e) {
    return false;
  }
  return Arrays.equals(b, HEADER_MAGIC);
}
 
Example 7
Project: openjdk-jdk10   File: AllowSearch.java   View Source Code Vote up 5 votes
private static void test(ImageReader reader, String format)
    throws IOException {
    boolean gotISE = false;
    File f = null;
    ImageInputStream stream = null;
    try {
        f = File.createTempFile("imageio", ".tmp");
        stream = ImageIO.createImageInputStream(f);
        reader.setInput(stream, true);

        try {
            int numImages = reader.getNumImages(true);
        } catch (IOException ioe) {
            gotISE = false;
        } catch (IllegalStateException ise) {
            gotISE = true;
        }
    } finally {
        if (stream != null) {
            stream.close();
        }

        reader.dispose();

        if (f != null) {
            Files.delete(f.toPath());
        }
    }

    if (!gotISE) {
        throw new RuntimeException("Failed to get desired exception for " +
                                   format + " reader!");
    }
}
 
Example 8
Project: sumo   File: TIFF.java   View Source Code Vote up 5 votes
/**
    * 
    * @param imageFile
    * @param band form files with multiple band
    */
public TIFF(File imageFile,int band) {
   	this.imageFile=imageFile;
       try {
           Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("tiff");
           boolean worked=false;
           while(readers.hasNext()&&!worked){
           	Object obj=readers.next();
           	if( obj instanceof TIFFImageReader){
           		reader = (TIFFImageReader)obj;
           		iis=ImageIO.createImageInputStream(imageFile);
           		reader.setInput(iis);
           		try{
           			xSize=reader.getWidth(band);
           			ySize=reader.getHeight(band);
           			bounds=new Rectangle(0,0,xSize,ySize);
           		}catch(Exception e){
           			bounds=null;
           			logger.warn("Problem reading size information");
           		}	
           		worked=true;
           	}else{
           		
           	}
           }
           if(!worked){
           	logger.warn("No reader avalaible for this image");
           }
       } catch (Exception ex) {
       	logger.error(ex.getMessage(),ex);
       }	
}
 
Example 9
Project: sucok-framework   File: ImageUtils.java   View Source Code Vote up 5 votes
public static BufferedImage read(String format, InputStream in) throws IOException {
	Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(format);
	ImageReader reader = (ImageReader) iterator.next();
	ImageInputStream iis = ImageIO.createImageInputStream(in);
	reader.setInput(iis, true);
	ImageReadParam param = reader.getDefaultReadParam();
	BufferedImage bi = reader.read(0, param);
	return bi;
}
 
Example 10
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 11
Project: featurea   File: GifFramesExtractor.java   View Source Code Vote up 5 votes
/**
 * @param object File or InputStream
 */
public static List<InputStream> getPngFrames(Object object) {
    try {
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(object);
        return getPngFrames(imageInputStream);
    } catch (IOException e) {
        e.printStackTrace();
        return new ArrayList<>();
    }
}
 
Example 12
Project: jdk8u-jdk   File: ShortStreamTest.java   View Source Code Vote up 5 votes
private static ImageInputStream createShortStream() {
    try {
        byte[] integerTestArray = new byte[] { 80 };
        ByteArrayInputStream bais = new ByteArrayInputStream(integerTestArray);

        return ImageIO.createImageInputStream(bais);
    } catch (IOException e) {
        return null;
    }
}
 
Example 13
Project: jdk8u-jdk   File: ReadAsGrayTest.java   View Source Code Vote up 5 votes
private static void doTest(int type) throws IOException {
    BufferedImage src = createTestImage(type);

    File f = new File("test.jpg");

    if (!ImageIO.write(src, "jpg", f)) {
        throw new RuntimeException("Failed to write test image.");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(f);
    ImageReader reader = ImageIO.getImageReaders(iis).next();
    reader.setInput(iis);

    Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0);
    ImageTypeSpecifier srgb = null;
    ImageTypeSpecifier gray = null;
    // look for gray and srgb types
    while ((srgb == null || gray == null) && types.hasNext()) {
        ImageTypeSpecifier t = types.next();
        if (t.getColorModel().getColorSpace().getType() == TYPE_GRAY) {
            gray = t;
        }
        if (t.getColorModel().getColorSpace() == sRGB) {
            srgb = t;
        }
    }
    if (gray == null) {
        throw new RuntimeException("No gray type available.");
    }
    if (srgb == null) {
        throw new RuntimeException("No srgb type available.");
    }

    System.out.println("Read as GRAY...");
    testType(reader, gray, src);

    System.out.println("Read as sRGB...");
    testType(reader, srgb, src);
}
 
Example 14
Project: openjdk-jdk10   File: ReadAsGrayTest.java   View Source Code Vote up 5 votes
private static void doTest(int type) throws IOException {
    BufferedImage src = createTestImage(type);

    File f = new File("test.jpg");

    if (!ImageIO.write(src, "jpg", f)) {
        throw new RuntimeException("Failed to write test image.");
    }

    ImageInputStream iis = ImageIO.createImageInputStream(f);
    ImageReader reader = ImageIO.getImageReaders(iis).next();
    reader.setInput(iis);

    Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0);
    ImageTypeSpecifier srgb = null;
    ImageTypeSpecifier gray = null;
    // look for gray and srgb types
    while ((srgb == null || gray == null) && types.hasNext()) {
        ImageTypeSpecifier t = types.next();
        if (t.getColorModel().getColorSpace().getType() == TYPE_GRAY) {
            gray = t;
        }
        if (t.getColorModel().getColorSpace() == sRGB) {
            srgb = t;
        }
    }
    if (gray == null) {
        throw new RuntimeException("No gray type available.");
    }
    if (srgb == null) {
        throw new RuntimeException("No srgb type available.");
    }

    System.out.println("Read as GRAY...");
    testType(reader, gray, src);

    System.out.println("Read as sRGB...");
    testType(reader, srgb, src);
}
 
Example 15
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 16
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 17
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 18
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 19
Project: openaudible   File: StandardArtwork.java   View Source Code Vote up 4 votes
public Object getImage() throws IOException {
    ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(getBinaryData()));
    BufferedImage bi = ImageIO.read(iis);
    return bi;
}
 
Example 20
Project: openjdk-jdk10   File: NoExtraBytesTest.java   View Source Code Vote up 3 votes
private void read(File f) throws IOException {
    ImageReader reader = ImageIO.getImageReadersByFormatName("BMP").next();

    ImageInputStream iis =
            ImageIO.createImageInputStream(new FileInputStream(f));

    reader.setInput(iis);

    iio_dst = reader.readAll(0, reader.getDefaultReadParam());
}