javax.imageio.ImageReader Java Examples

The following examples show how to use javax.imageio.ImageReader. 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: InputImageTests.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageReader reader = ictx.reader;
    final boolean seekForwardOnly = ictx.seekForwardOnly;
    final boolean ignoreMetadata = ictx.ignoreMetadata;
    do {
        try {
            ImageInputStream iis = ictx.createImageInputStream();
            reader.setInput(iis, seekForwardOnly, ignoreMetadata);
            reader.read(0);
            reader.reset();
            iis.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #2
Source File: InputImageTests.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageReader reader = ictx.reader;
    final boolean seekForwardOnly = ictx.seekForwardOnly;
    final boolean ignoreMetadata = ictx.ignoreMetadata;
    do {
        try {
            ImageInputStream iis = ictx.createImageInputStream();
            reader.setInput(iis, seekForwardOnly, ignoreMetadata);
            reader.read(0);
            reader.reset();
            iis.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #3
Source File: TruncatedImageWarningTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: AnimationImpl.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public static Point getPixelOffsets(ImageReader reader, int num) throws IOException {
    IIOMetadata meta = reader.getImageMetadata(num);
    Point point = new Point(-1,-1);
    Node root = meta.getAsTree("javax_imageio_1.0");
    //printNodeTree(root);
    for (Node c = root.getFirstChild(); c != null; c = c.getNextSibling()) {
        String name = c.getNodeName();
        if ("Dimension".equals(name)) {
            for (c = c.getFirstChild(); c != null; c = c.getNextSibling()) {
                name = c.getNodeName();
                if ("HorizontalPixelOffset".equals(name))
                    point.x = getValueAttribute(c);
                else if ("VerticalPixelOffset".equals(name))
                    point.y = getValueAttribute(c);
            }
            return point;
        }
    }
    return point;
}
 
Example #5
Source File: ImageLoadJaiTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: InputImageTests.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageReader reader = ictx.reader;
    final boolean seekForwardOnly = ictx.seekForwardOnly;
    final boolean ignoreMetadata = ictx.ignoreMetadata;
    do {
        try {
            ImageInputStream iis = ictx.createImageInputStream();
            reader.setInput(iis, seekForwardOnly, ignoreMetadata);
            reader.read(0);
            reader.reset();
            iis.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #7
Source File: InputImageTests.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    final Context ictx = (Context)ctx;
    final ImageReader reader = ictx.reader;
    final boolean seekForwardOnly = ictx.seekForwardOnly;
    final boolean ignoreMetadata = ictx.ignoreMetadata;
    do {
        try {
            ImageInputStream iis = ictx.createImageInputStream();
            reader.setInput(iis, seekForwardOnly, ignoreMetadata);
            reader.getImageMetadata(0);
            reader.reset();
            iis.close();
            ictx.closeOriginalStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } while (--numReps >= 0);
}
 
Example #8
Source File: ImageIOHelper.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
public static File createImage(File imageFile, String imageFormat) {
	File tempFile = null;
	try {
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
		ImageReader reader = readers.next();

		ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
		reader.setInput(iis);
		// Read the stream metadata
		IIOMetadata streamMetadata = reader.getStreamMetadata();

		// Set up the writeParam
		TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
		tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

		// Get tif writer and set output to file
		Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("tiff");
		ImageWriter writer = writers.next();

		BufferedImage bi = reader.read(0);
		IIOImage image = new IIOImage(bi, null, reader.getImageMetadata(0));
		tempFile = tempImageFile(imageFile);
		ImageOutputStream ios = ImageIO.createImageOutputStream(tempFile);
		writer.setOutput(ios);
		writer.write(streamMetadata, image, tiffWriteParam);
		ios.close();

		writer.dispose();
		reader.dispose();
	} catch (Exception exc) {
		exc.printStackTrace();
	}
	return tempFile;
}
 
Example #9
Source File: UserPluginMetadataFormatTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void computeRegions(ImageReadParam param,
                                  int srcWidth,
                                  int srcHeight,
                                  BufferedImage image,
                                  Rectangle srcRegion,
                                  Rectangle destRegion) {
    ImageReader.computeRegions(param,
                               srcWidth,
                               srcHeight,
                               image,
                               srcRegion,
                               destRegion);
}
 
Example #10
Source File: BigBufferedImage.java    From OpenRS with GNU General Public License v3.0 5 votes vote down vote up
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 #11
Source File: StreamResetTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    IOException expectedException = null;
    TestStream iis = new TestStream();

    ImageReader wbmp = ImageIO.getImageReadersByFormatName("WBMP").next();
    if (wbmp == null) {
        System.out.println("No WBMP reader: skip the test");
        return;
    }

    ImageReaderSpi spi = wbmp.getOriginatingProvider();

    iis.checkPosition();

    try {
        spi.canDecodeInput(iis);
    } catch (IOException e) {
        expectedException = e;
    }

    if (expectedException == null) {
        throw new RuntimeException("Test FAILED: stream was not used");
    }

    iis.checkPosition();

    System.out.println("Test PASSED");

}
 
Example #12
Source File: MCRThumbnailServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private BufferedImage getThumbnail(Path iviewFile, boolean centered) throws IOException, JDOMException {
    BufferedImage level1Image;
    try (FileSystem fs = MCRIView2Tools.getFileSystem(iviewFile)) {
        Path iviewFileRoot = fs.getRootDirectories().iterator().next();
        MCRTiledPictureProps props = MCRTiledPictureProps.getInstanceFromDirectory(iviewFileRoot);
        //get next bigger zoomLevel and scale image to THUMBNAIL_SIZE
        ImageReader reader = MCRIView2Tools.getTileImageReader();
        try {
            level1Image = MCRIView2Tools.getZoomLevel(iviewFileRoot, props, reader,
                Math.min(1, props.getZoomlevel()));
        } finally {
            reader.dispose();
        }
    }
    final double width = level1Image.getWidth();
    final double height = level1Image.getHeight();
    final int newWidth = width < height ? (int) Math.ceil(thumbnailSize * width / height) : thumbnailSize;
    final int newHeight = width < height ? thumbnailSize : (int) Math.ceil(thumbnailSize * height / width);
    //if centered make transparent image
    int imageType = centered ? BufferedImage.TYPE_INT_ARGB : MCRImage.getImageType(level1Image);
    //if centered make thumbnailSize x thumbnailSize image
    final BufferedImage bicubic = new BufferedImage(centered ? thumbnailSize : newWidth, centered ? thumbnailSize
        : newHeight, imageType);
    final Graphics2D bg = bicubic.createGraphics();
    try {
        bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        int x = centered ? (thumbnailSize - newWidth) / 2 : 0;
        int y = centered ? (thumbnailSize - newHeight) / 2 : 0;
        if (x != 0 && y != 0) {
            LOGGER.warn("Writing at position {},{}", x, y);
        }
        bg.drawImage(level1Image, x, y, x + newWidth, y + newHeight, 0, 0, (int) Math.ceil(width),
            (int) Math.ceil(height), null);
    } finally {
        bg.dispose();
    }
    return bicubic;
}
 
Example #13
Source File: ReadingInterruptionTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void imageProgress(ImageReader source,
                          float percentageDone)
{
    if (20f < percentageDone && percentageDone < 80f) {
        Thread t = new Thread(action);
        t.start();
    }
}
 
Example #14
Source File: ReadAsGrayTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
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
Source File: UserPluginMetadataFormatTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static BufferedImage getDestination(ImageReadParam param,
                                           Iterator imageTypes,
                                           int width,
                                           int height)
  throws IIOException {
    return ImageReader.getDestination(param,
                                      imageTypes,
                                      width,
                                      height);
}
 
Example #16
Source File: GetReaderWriterInfo.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testGetReaderFormatNames() {
    String[] names = ImageIO.getReaderFormatNames();
    for (String n : names) {
        Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(n);
        if (!it.hasNext()) {
            throw new RuntimeException("getReaderFormatNames returned " +
                                       "an unknown name: " + n);
        }
    }
}
 
Example #17
Source File: ReadAsGrayTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #18
Source File: ReadAsGrayTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void testType(ImageReader reader,
                             ImageTypeSpecifier t,
                             BufferedImage src)
    throws IOException
{
    ImageReadParam p = reader.getDefaultReadParam();
    p.setDestinationType(t);
    BufferedImage dst = reader.read(0, p);

    verify(src, dst, t);
}
 
Example #19
Source File: UserPluginMetadataFormatTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void computeRegions(ImageReadParam param,
                                  int srcWidth,
                                  int srcHeight,
                                  BufferedImage image,
                                  Rectangle srcRegion,
                                  Rectangle destRegion) {
    ImageReader.computeRegions(param,
                               srcWidth,
                               srcHeight,
                               image,
                               srcRegion,
                               destRegion);
}
 
Example #20
Source File: ReadAsGrayTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testType(ImageReader reader,
                             ImageTypeSpecifier t,
                             BufferedImage src)
    throws IOException
{
    ImageReadParam p = reader.getDefaultReadParam();
    p.setDestinationType(t);
    BufferedImage dst = reader.read(0, p);

    verify(src, dst, t);
}
 
Example #21
Source File: ExifUtils.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the orientation obtained from the Exif metadata.
 * 
 * @param reader		An {@link ImageReader} which is reading the
 * 						target image.
 * @param imageIndex	The index of the image from which the Exif
 * 						metadata should be read from.
 * @return				The orientation information obtained from the
 * 						Exif metadata, as a {@link Orientation} enum.
 * @throws IOException				When an error occurs during reading.
 * @throws IllegalArgumentException	If the {@link ImageReader} does not
 * 									have the target image set, or if the
 * 									reader does not have a JPEG open.
 */
public static Orientation getExifOrientation(ImageReader reader, int imageIndex) throws IOException
{
	IIOMetadata metadata = reader.getImageMetadata(imageIndex);
	Node rootNode = metadata.getAsTree("javax_imageio_jpeg_image_1.0");
	
	NodeList childNodes = rootNode.getChildNodes();
	
	// Look for the APP1 containing Exif data, and retrieve it.
	for (int i = 0; i < childNodes.getLength(); i++)
	{
		if ("markerSequence".equals(childNodes.item(i).getNodeName()))
		{
			NodeList markerSequenceChildren = childNodes.item(i).getChildNodes();
			
			for (int j = 0; j < markerSequenceChildren.getLength(); j++)
			{
				IIOMetadataNode metadataNode = (IIOMetadataNode)(markerSequenceChildren.item(j));
				
				byte[] bytes = (byte[])metadataNode.getUserObject();
				if (bytes == null)
				{
					continue;
				}
				
				byte[] magicNumber = new byte[4];
				ByteBuffer.wrap(bytes).get(magicNumber);
				
				if (EXIF_MAGIC_STRING.equals(new String(magicNumber)))
				{
					return getOrientationFromExif(bytes);
				}
			}
		}
	}
	
	return null;
}
 
Example #22
Source File: ReadingInterruptionTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void sequenceStarted(ImageReader source,
int minIndex) {}
 
Example #23
Source File: UserPluginMetadataFormatTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static Rectangle getSourceRegion(ImageReadParam param,
                                        int srcWidth,
                                        int srcHeight) {
    return ImageReader.getSourceRegion(param, srcWidth, srcHeight);
}
 
Example #24
Source File: InputImageTests.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void thumbnailStarted(ImageReader source,
int imageIndex, int thumbnailIndex) {}
 
Example #25
Source File: ReadingInterruptionTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void thumbnailStarted(ImageReader source,
int imageIndex,
int thumbnailIndex) {}
 
Example #26
Source File: JFIFMarkerSegment.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public void imageProgress(ImageReader source,
                          float percentageDone) {
    reader.thumbnailProgress(percentageDone);
}
 
Example #27
Source File: ReadingInterruptionTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void imageStarted(ImageReader source,
int imageIndex) {}
 
Example #28
Source File: ReadingInterruptionTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void thumbnailStarted(ImageReader source,
int imageIndex,
int thumbnailIndex) {}
 
Example #29
Source File: ReadingInterruptionTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void setTarget(ImageReader target) {
    this.target = target;
}
 
Example #30
Source File: ReadingInterruptionTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public void sequenceStarted(ImageReader source,
int minIndex) {}