Java Code Examples for javax.imageio.ImageReader#read()

The following examples show how to use javax.imageio.ImageReader#read() . 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 openjdk-8 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: ImageUtils.java    From springboot-admin with Apache License 2.0 6 votes vote down vote up
private static BufferedImage readBuffereImage(ImageReader reader, int w, int h) throws IOException {
	ImageReadParam param = reader.getDefaultReadParam();
	int srcWidth = reader.getWidth(0);
	int srcHeight = reader.getHeight(0);

	Rectangle rect = null;

	if ((float) w / h > (float) srcWidth / srcHeight) {
		h = h * srcWidth / w;
		w = srcWidth;
		rect = new Rectangle(0, (srcHeight - h) / 2, w, h);
	} else {
		w = w * srcHeight / h;
		h = srcHeight;
		rect = new Rectangle((srcWidth - w) / 2, 0, w, h);
	}
	param.setSourceRegion(rect);
	BufferedImage srcBuffered = reader.read(0, param);
	return srcBuffered;
}
 
Example 3
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 testExtractPagesFromMultiPageTiffCompression7() throws Exception {

    File sourceImageFile = getImageFile("tiff", "test-multi-rgb-compression-type-7.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 10 pages", 10, pages);
}
 
Example 4
Source File: TruncatedImageWarningTest.java    From openjdk-jdk9 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 5
Source File: TruncatedImageWarningTest.java    From jdk8u60 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 6
Source File: SourceImage.java    From screenstudio with GNU General Public License v3.0 6 votes vote down vote up
private BufferedImage[] readGif(File input) {
    BufferedImage[] images = new BufferedImage[0];
    try {
        ImageReader reader = ImageIO.getImageReadersByFormatName("gif").next();
        ImageInputStream stream = ImageIO.createImageInputStream(input);
        reader.setInput(stream);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int index = 0; index < count; index++) {
            BufferedImage frame = reader.read(index);
            images[index] = new BufferedImage(mBounds.width, mBounds.height, mImageType);
            images[index].createGraphics().drawImage(frame.getScaledInstance(mBounds.width, mBounds.height, Image.SCALE_SMOOTH), 0, 0, null);
            data = ((DataBufferByte) images[index].getRaster().getDataBuffer()).getData();
        }
        mTimeDelay = 100;

    } catch (IOException ex) {

    }
    return images;
}
 
Example 7
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 8
Source File: ReadAsGrayTest.java    From openjdk-jdk8u-backup 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 9
Source File: ReadAsGrayTest.java    From jdk8u-dev-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 10
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 11
Source File: AnimatedMessage.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public List<BufferedImage> getFrames(File input) {
    List<BufferedImage> images = new ArrayList<BufferedImage>();
    try {
        ImageReader reader = ImageIO.getImageReadersBySuffix("GIF").next();
        ImageInputStream in = ImageIO.createImageInputStream(input);
        reader.setInput(in);
        for (int i = 0, count = reader.getNumImages(true); i < count; i++) {
            BufferedImage image = reader.read(i); // read next frame from gif
            images.add(image);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return images;
}
 
Example 12
Source File: MultiReadTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void test(String format) throws IOException {
    System.out.println("Format: " + format);

    BufferedImage src = createSrc();

    ImageInputStream iis = prepareInput(src, format);

    ImageReader reader = ImageIO.getImageReaders(iis).next();

    reader.setInput(iis);

    ImageReadParam p = reader.getDefaultReadParam();
    int cnt = 0;
    do {
        System.out.println("cnt: " + cnt);
        p.setSourceRegion(new Rectangle(width / 4, height / 4,
                                        width / 2, height / 2));

        BufferedImage dst = reader.read(0, p);

        final Color c = new Color(dst.getRGB(10, 10), true);

        if (!sameColor(c, srcColor)) {
            throw new RuntimeException(
                String.format("Test failed: read color 0x%X\n",
                              c.getRGB()));
        }
    } while (++cnt < max);
}
 
Example 13
Source File: PageImageWriter.java    From sejda with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the input file is a PNG using ICC Gray color model
 * If that's the case, converts to RGB and returns the file path
 */
private static Optional<SeekableSource> convertICCGrayPngIf(SeekableSource source) throws IOException, TaskIOException {
    try {
        if (FileType.PNG.equals(getFileType(source))) {
            try (ImageInputStream iis = ImageIO.createImageInputStream(source.asNewInputStream())) {
                ImageReader reader = ImageIO.getImageReadersByFormatName("png").next();
                boolean isICCGray = false;
                try {
                    ImageIO.setUseCache(false);
                    reader.setInput(iis);
                    for (Iterator<ImageTypeSpecifier> it = reader.getImageTypes(0); it.hasNext(); ) {
                        ImageTypeSpecifier typeSpecifier = it.next();
                        ColorSpace colorSpace = typeSpecifier.getColorModel().getColorSpace();
                        if (colorSpace instanceof ICC_ColorSpace && ((ICC_ColorSpace) colorSpace).getProfile() instanceof ICC_ProfileGray) {
                            isICCGray = true;
                            break;
                        }
                    }

                    if (isICCGray) {
                        LOG.debug("Detected a Gray PNG image, will convert to RGB and save to a new file");
                        // convert to rgb
                        BufferedImage original = reader.read(0);
                        BufferedImage rgb = toARGB(original);
                        File tmpFile = IOUtils.createTemporaryBuffer();
                        ImageIO.write(rgb, "png", tmpFile);
                        return Optional.of(SeekableSources.seekableSourceFrom(tmpFile));
                    }
                } finally {
                    reader.dispose();
                }
            }
        }
    } catch (IIOException e) {
        LOG.debug("Failed convertICCGrayPngIf()", e);
    }

    return Optional.empty();
}
 
Example 14
Source File: AnimationTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void checkAnimation() throws IOException {
    ImageReader r = ImageIO.getImageReadersByFormatName("GIF").next();
    r.setInput(ImageIO.createImageInputStream(new File(fname)));

    int n = r.getNumImages(true);
    for (int i = 0; i < n; i++) {
        BufferedImage f = r.read(i);
        checkFrame(i, f);
    }
    System.out.println("Test passed.");
}
 
Example 15
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 16
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 17
Source File: ReadAsGrayTest.java    From dragonwell8_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 18
Source File: ImageIOHelper.java    From JewelCrawler with GNU General Public License v3.0 5 votes vote down vote up
public static BufferedImage getImage(File imageFile) {
	BufferedImage al = null;
	try {
		String imageFileName = imageFile.getName();
		String imageFormat = imageFileName.substring(imageFileName.lastIndexOf('.') + 1);
		Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
		ImageReader reader = readers.next();

		if (reader == null) {
			JOptionPane.showConfirmDialog(null,
					"Need to install JAI Image I/O package.\nhttps://jai-imageio.dev.java.net");
			return null;
		}

		ImageInputStream iis = ImageIO.createImageInputStream(imageFile);
		reader.setInput(iis);

		al = reader.read(0);

		reader.dispose();
	} catch (IOException ioe) {
		System.err.println(ioe.getMessage());
	} catch (Exception e) {
		System.err.println(e.getMessage());
	}

	return al;
}
 
Example 19
Source File: PageImageWriter.java    From sejda with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Checks if the input file is a JPEG using CMYK
 * If that's the case, converts to RGB and returns the file path
 */
private static Optional<SeekableSource> convertCMYKJpegIf(SeekableSource source) throws IOException, TaskIOException {
    try {
        if (FileType.JPEG.equals(getFileType(source))) {
            try (ImageInputStream iis = ImageIO.createImageInputStream(source.asNewInputStream())) {
                ImageReader reader = ImageIO.getImageReadersByFormatName("jpg").next();
                boolean isCmyk = false;
                try {
                    ImageIO.setUseCache(false);
                    reader.setInput(iis);
                    for (Iterator<ImageTypeSpecifier> it = reader.getImageTypes(0); it.hasNext(); ) {
                        ImageTypeSpecifier typeSpecifier = it.next();
                        if (typeSpecifier.getColorModel().getColorSpace().getType() == ColorSpace.TYPE_CMYK) {
                            isCmyk = true;
                        }
                    }

                    if (isCmyk) {
                        LOG.debug("Detected a CMYK JPEG image, will convert to RGB and save to a new file");
                        // convert to rgb
                        // twelvemonkeys JPEG plugin already converts it to rgb when reading the image
                        // just write it out
                        BufferedImage image = reader.read(0);
                        File tmpFile = IOUtils.createTemporaryBuffer();
                        ImageIO.write(image, "jpg", tmpFile);
                        return Optional.of(SeekableSources.seekableSourceFrom(tmpFile));
                    }
                } finally {
                    reader.dispose();
                }
            }
        }
    } catch (IIOException e) {
        if(e.getMessage().startsWith("Not a JPEG stream")) {
            // this was a different image format with a JPEG extension
        } else {
            throw e;
        }
    }

    return Optional.empty();
}
 
Example 20
Source File: TestAxisCameraDriver.java    From sensorhub with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void handleEvent(Event<?> e)
{
    assertTrue(e instanceof SensorDataEvent);
    SensorDataEvent newDataEvent = (SensorDataEvent)e;
    
    if (newDataEvent.getSource().getClass().equals(AxisVideoOutput.class))
    {
     DataComponent camDataStruct = newDataEvent.getRecordDescription().copy();
     camDataStruct.setData(newDataEvent.getRecords()[0]);
     
     actualHeight = camDataStruct.getComponent(1).getComponentCount();
     actualWidth = camDataStruct.getComponent(1).getComponent(0).getComponentCount();
     dataBlockSize = newDataEvent.getRecords()[0].getAtomCount();
     		
     byte[] frameData = (byte[])camDataStruct.getComponent(1).getData().getUnderlyingObject();
                    
     /*// use RGB data directly
     byte[] destArray = ((DataBufferByte)img.getRaster().getDataBuffer()).getData();
     System.arraycopy(frameData, 0, destArray, 0, dataBlockSize-1);*/
     
     // uncompress JPEG data
     BufferedImage rgbImage;
        try
        {
            InputStream imageStream = new ByteArrayInputStream(frameData);                               
            ImageInputStream input = ImageIO.createImageInputStream(imageStream); 
            Iterator<ImageReader> readers = ImageIO.getImageReadersByMIMEType("image/jpeg");
            ImageReader reader = readers.next();
            reader.setInput(input);
            rgbImage = reader.read(0);
            videoWindow.getContentPane().getGraphics().drawImage(rgbImage, 0, 0, null);
        }
        catch (IOException e1)
        {
            throw new RuntimeException(e1);
        }
        
        frameCount++;
    }
    else if (newDataEvent.getSource().getClass().equals(AxisSettingsOutput.class))
    {
    	DataComponent ptzParams = newDataEvent.getRecordDescription().copy();
    	ptzParams.setData(newDataEvent.getRecords()[0]);
    	System.out.println(ptzParams);
    }
    
    synchronized (this) { this.notify(); }
}