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

The following examples show how to use javax.imageio.ImageIO#createImageInputStream() . These examples are extracted from open source projects. 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
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 2
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
public static void main(String[] args) throws IOException {

        String sep = System.getProperty("file.separator");
        String dir = System.getProperty("test.src", ".");
        String filePath = dir+sep+fileName;
        System.out.println("Test file: " + filePath);
        File f = new File(filePath);
        ImageInputStream in = ImageIO.createImageInputStream(f);
        ImageReader reader = ImageIO.getImageReaders(in).next();
        TruncatedImageWarningTest twt = new TruncatedImageWarningTest();
        reader.addIIOReadWarningListener(twt);
        reader.setInput(in);
        reader.read(0);
        if (!twt.receivedWarning) {
            throw new RuntimeException("No expected warning");
        }
    }
 
Example 4
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 5
/**
 * 等比缩放,居中剪切
 *
 * @param src
 * @param dest
 * @param w
 * @param h
 * @throws IOException
 */
public static void scale(String src, String dest, int w, int h) throws IOException {

    if (notImageExtName(src)) {
        throw new IllegalArgumentException("只支持如下几种图片格式:jpg、jpeg、png、bmp");
    }

    Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName(getExtName(src));
    ImageReader reader = (ImageReader) iterator.next();

    InputStream in = new FileInputStream(src);
    ImageInputStream iis = ImageIO.createImageInputStream(in);
    reader.setInput(iis);

    BufferedImage srcBuffered = readBuffereImage(reader, w, h);
    BufferedImage targetBuffered = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

    Graphics graphics = targetBuffered.getGraphics();
    graphics.drawImage(srcBuffered.getScaledInstance(w, h, Image.SCALE_DEFAULT), 0, 0, null); // 绘制缩小后的图

    graphics.dispose();
    srcBuffered.flush();
    save(targetBuffered, dest);
    targetBuffered.flush();
}
 
Example 6
public static int[] getImageDimensions(File f) throws IOException {
    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 7
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 8
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 9
public static void main(String[] args) throws IOException {

        String sep = System.getProperty("file.separator");
        String dir = System.getProperty("test.src", ".");
        String filePath = dir+sep+fileName;
        System.out.println("Test file: " + filePath);
        File f = new File(filePath);
        ImageInputStream in = ImageIO.createImageInputStream(f);
        ImageReader reader = ImageIO.getImageReaders(in).next();
        TruncatedImageWarningTest twt = new TruncatedImageWarningTest();
        reader.addIIOReadWarningListener(twt);
        reader.setInput(in);
        reader.read(0);
        if (!twt.receivedWarning) {
            throw new RuntimeException("No expected warning");
        }
    }
 
Example 10
Source Project: htmlunit   File: HtmlImage.java    License: Apache License 2.0 6 votes vote down vote up
private void readImageIfNeeded() throws IOException {
    downloadImageIfNeeded();
    if (imageData_ == null) {
        if (null == imageWebResponse_) {
            throw new IOException("No image response available (src='" + getSrcAttribute() + "')");
        }
        @SuppressWarnings("resource")
        final ImageInputStream iis = ImageIO.createImageInputStream(imageWebResponse_.getContentAsStream());
        final Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        if (!iter.hasNext()) {
            iis.close();
            throw new IOException("No image detected in response");
        }
        final ImageReader imageReader = iter.next();
        imageReader.setInput(iis);
        imageData_ = new ImageData(imageReader);

        // dispose all others
        while (iter.hasNext()) {
            iter.next().dispose();
        }
    }
}
 
Example 11
private static ImageAndResolution readAndDisplayMetadataPNG(DSSDocument image) throws IOException {
	try (InputStream is = image.openStream(); ImageInputStream iis = ImageIO.createImageInputStream(is)) {

		ImageReader reader = getImageReader("png");
		// attach source to the reader
		reader.setInput(iis, true);
		
		int hdpi = DEFAULT_DPI;
		int vdpi = DEFAULT_DPI;

		if (isSupportedColorSpace(reader)) {
			// read metadata of first image
			IIOMetadata metadata = reader.getImageMetadata(0);

			double mm2inch = 25.4;

			Element node = (Element) metadata.getAsTree("javax_imageio_1.0");
			NodeList lst = node.getElementsByTagName("HorizontalPixelSize");
			if (lst != null && lst.getLength() == 1) {
				hdpi = (int) (mm2inch / Float.parseFloat(((Element) lst.item(0)).getAttribute("value")));
			} else {
				LOG.debug("Cannot get HorizontalPixelSize value. Using the default dpi [{}]", DEFAULT_DPI);
			}

			lst = node.getElementsByTagName("VerticalPixelSize");
			if (lst != null && lst.getLength() == 1) {
				vdpi = (int) (mm2inch / Float.parseFloat(((Element) lst.item(0)).getAttribute("value")));
			} else {
				LOG.debug("Cannot get HorizontalPixelSize value. Using the default dpi [{}]", DEFAULT_DPI);
			}
		} else {
			LOG.warn("Cannot read metadata of the image with name [{}]. The color space is not supported. "
					+ "Using the default dpi with value [{}]", image.getName(), DEFAULT_DPI);
		}

		return new ImageAndResolution(image, hdpi, vdpi);
	}
}
 
Example 12
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 13
public static void main(String[] argv){
  try{
    String           test = "335566\n%%EOF\n [1] [1 2 ] [1 2 3] [1 2 3 4] [1 2 3 4 5] [1 2 R] [0 1 2 R] [0 1 R 2 3 R] [0 1 2 3 4 R] [0 1 2 3 4  5 R] [0 1 0 R 2 0 R 3 0][0] [0 1] (Klasse wie geht's\\t?\\\n Hallo)  true \\ << 101 10.2 >>  [false  null]  /NA***;_ME<41>  %comment\n <4142303961>";
    InputStream      in   = new ByteArrayInputStream(test.getBytes());
    ImageInputStream iin  = ImageIO.createImageInputStream(in);
    PDFScanner       s    = new PDFScanner(null,iin);

    while(s.symbol!=T_EOF){
      s.scan();      
      switch(s.symbol){
      case T_STRING: System.err.println("string = "+s.str); break;
      case T_NAME:   System.err.println("name   = "+s.str); break;
      case T_TRUE:   System.err.println("true   = "+s.str); break;
      case T_FALSE:  System.err.println("false  = "+s.str); break;
      case T_NULL:   System.err.println("null   = "+s.str); break;
      case T_INTEGER:   System.err.println("int = "+s.intval); break;
      case T_REAL:   System.err.println("real = "+s.realval); break;
      case T_ARRAY_START:      System.err.println("array start"); break;
      case T_ARRAY_END:        System.err.println("array end");   break;
      case T_DICTIONARY_START: System.err.println("dict start");  break;
      case T_DICTIONARY_END:   System.err.println("dict end");    break;
      case T_R:      System.err.println("R "+s.objectNumber+" "+s.generationNumber); break;
      default:       System.err.println("symbol    = "+s.symbol); break;
      }
    }      
  }catch(Exception e){
    e.printStackTrace();
  }
}
 
Example 14
Source Project: cs-actions   File: OcrService.java    License: Apache License 2.0 5 votes vote down vote up
private static String deskewImage(String filePath) throws IOException {
    File imageFile = new File(filePath);
    BufferedImage bi = ImageIO.read(imageFile);
    ImageDeskew id = new ImageDeskew(bi);

    double imageSkewAngle = id.getSkewAngle(); // determine skew angle
    if ((imageSkewAngle > MINIMUM_DESKEW_THRESHOLD || imageSkewAngle < -(MINIMUM_DESKEW_THRESHOLD))) {
        bi = ImageHelper.rotateImage(bi, -imageSkewAngle); // deskew image
    }

    ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
    Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);

    if (!iter.hasNext()) {
        throw new RuntimeException("No readers found!");
    }

    ImageReader reader = iter.next();
    String formatName = reader.getFormatName();
    iis.close();

    String tempImage = Files.createTempFile("tempImage", formatName).toString();

    ImageIO.write(bi, formatName, new File(tempImage));

    return tempImage;
}
 
Example 15
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 16
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 17
private static void doTest(BufferedImage src,
                           String compressionType,
                           int compressionMode) throws IOException
{

    ImageWriter iw =  (ImageWriter)ImageIO.getImageWritersBySuffix("bmp").next();
    if (iw == null) {
        throw new RuntimeException("No available writer. Test failed.");
    }

    IIOImage iioImg = new IIOImage(src, null, null);
    ImageWriteParam param = iw.getDefaultWriteParam();


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

    System.out.println("Compression Type is " + compressionType);
    System.out.println("Compression Mode is " + compressionMode);

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compressionType);
    if (compressionMode != ImageWriteParam.MODE_EXPLICIT) {
        param.setCompressionMode(compressionMode);
    }
    try {
        iw.write(null, iioImg, param);
    } catch (IOException e) {
        int bpp = src.getColorModel().getPixelSize();
        if (compressionMode == ImageWriteParam.MODE_EXPLICIT) {
            if ((compressionType.equals("BI_RLE4") && bpp != 4)
                || (compressionType.equals("BI_RLE8") && bpp != 8))
            {
                System.out.println("Can not encode "+ bpp+ "bpp image as"
                                  + compressionType);
                return;
            } else {
                throw new RuntimeException("Unable to encode "
                                           + bpp + "bpp image as "
                                           + compressionType
                                           + ". Test failed");
            }
        }
    }
    baos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);

    BufferedImage dst = ImageIO.read(iis);

    int w = src.getWidth();
    int h = src.getHeight();

    Object dstPixel = dst.getRaster().getDataElements(w/2, h/2, null);
    Object srcPixel = src.getRaster().getDataElements(w/2, h/2, null);

    if ( (src.getColorModel().getRed(srcPixel)
          != dst.getColorModel().getRed(dstPixel))
         || (src.getColorModel().getGreen(srcPixel)
             != dst.getColorModel().getGreen(dstPixel))
         || (src.getColorModel().getBlue(srcPixel)
             != dst.getColorModel().getBlue(dstPixel))
         || (src.getColorModel().getAlpha(srcPixel)
             != dst.getColorModel().getAlpha(dstPixel)) ) {

        showPixel(src, w/2, h/2);
        showPixel(dst, w/2, h/2);

        throw new RuntimeException(
            "Colors are different: " +
            Integer.toHexString(src.getColorModel().getRGB(srcPixel))
            + " and " +
            Integer.toHexString(dst.getColorModel().getRGB(dstPixel)));
    }

}
 
Example 18
Source Project: syndesis   File: ConnectorsITCase.java    License: Apache License 2.0 4 votes vote down vote up
@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")));

    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()).as("Wrong image height").isEqualTo(106d);
                assertThat(dimensions.getWidth()).as("Wrong image width").isEqualTo(106d);
            } finally {
                reader.dispose();
            }
        }
    }
}
 
Example 19
private static void doTest(BufferedImage src,
                           String compressionType,
                           int compressionMode) throws IOException
{

    ImageWriter iw =  (ImageWriter)ImageIO.getImageWritersBySuffix("bmp").next();
    if (iw == null) {
        throw new RuntimeException("No available writer. Test failed.");
    }

    IIOImage iioImg = new IIOImage(src, null, null);
    ImageWriteParam param = iw.getDefaultWriteParam();


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

    System.out.println("Compression Type is " + compressionType);
    System.out.println("Compression Mode is " + compressionMode);

    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionType(compressionType);
    if (compressionMode != ImageWriteParam.MODE_EXPLICIT) {
        param.setCompressionMode(compressionMode);
    }
    try {
        iw.write(null, iioImg, param);
    } catch (IOException e) {
        int bpp = src.getColorModel().getPixelSize();
        if (compressionMode == ImageWriteParam.MODE_EXPLICIT) {
            if ((compressionType.equals("BI_RLE4") && bpp != 4)
                || (compressionType.equals("BI_RLE8") && bpp != 8))
            {
                System.out.println("Can not encode "+ bpp+ "bpp image as"
                                  + compressionType);
                return;
            } else {
                throw new RuntimeException("Unable to encode "
                                           + bpp + "bpp image as "
                                           + compressionType
                                           + ". Test failed");
            }
        }
    }
    baos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);

    BufferedImage dst = ImageIO.read(iis);

    int w = src.getWidth();
    int h = src.getHeight();

    Object dstPixel = dst.getRaster().getDataElements(w/2, h/2, null);
    Object srcPixel = src.getRaster().getDataElements(w/2, h/2, null);

    if ( (src.getColorModel().getRed(srcPixel)
          != dst.getColorModel().getRed(dstPixel))
         || (src.getColorModel().getGreen(srcPixel)
             != dst.getColorModel().getGreen(dstPixel))
         || (src.getColorModel().getBlue(srcPixel)
             != dst.getColorModel().getBlue(dstPixel))
         || (src.getColorModel().getAlpha(srcPixel)
             != dst.getColorModel().getAlpha(dstPixel)) ) {

        showPixel(src, w/2, h/2);
        showPixel(dst, w/2, h/2);

        throw new RuntimeException(
            "Colors are different: " +
            Integer.toHexString(src.getColorModel().getRGB(srcPixel))
            + " and " +
            Integer.toHexString(dst.getColorModel().getRGB(dstPixel)));
    }

}
 
Example 20
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());
}