Example usage for javax.imageio ImageReader read

List of usage examples for javax.imageio ImageReader read

Introduction

In this page you can find the example usage for javax.imageio ImageReader read.

Prototype

public abstract BufferedImage read(int imageIndex, ImageReadParam param) throws IOException;

Source Link

Document

Reads the image indexed by imageIndex and returns it as a complete BufferedImage , using a supplied ImageReadParam .

Usage

From source file:Main.java

public static BufferedImage readFragment(InputStream stream, Rectangle rect) throws IOException {
    ImageInputStream imageStream = ImageIO.createImageInputStream(stream);
    ImageReader reader = ImageIO.getImageReaders(imageStream).next();
    ImageReadParam param = reader.getDefaultReadParam();

    param.setSourceRegion(rect);//from   www . ja  va 2s. co m
    reader.setInput(imageStream, true, true);
    BufferedImage image = reader.read(0, param);

    reader.dispose();
    imageStream.close();

    return image;
}

From source file:common.utils.ImageUtils.java

/**
 * closes iis/*ww  w .j  a v a 2 s.com*/
 * @param iis
 * @return image from given stream or null if no readers found
 * @throws java.io.IOException
 */
public static BufferedImageHolder readImage(ImageInputStream iis) throws IOException {
    ImageReader reader = getImageReader(iis);
    if (reader == null) {
        iis.close();
        return null;
    }
    reader.setInput(iis, true, true);
    ImageReadParam param = reader.getDefaultReadParam();
    String format_name = reader.getFormatName();
    BufferedImage bi;
    try {
        bi = reader.read(0, param);
    } finally {
        reader.dispose();
        iis.close();
    }
    return new BufferedImageHolder(bi, format_name);
}

From source file:com.shending.support.CompressPic.java

public static void cut(String srcFile, String dstFile, int widthRange, int heightRange) {
    int x = 0;/*from   www .  j a v  a 2 s  .c o  m*/
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        newWidth = oldHeight * widthRange / heightRange;
        if (newWidth < oldWidth) {
            newHeight = oldHeight;
            x = (oldWidth - newWidth) / 2;
        } else {
            newWidth = oldWidth;
            newHeight = oldWidth * heightRange / widthRange;
            y = (oldHeight - newHeight) / 2;
        }
        Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
        param.setSourceRegion(rectangle);
        BufferedImage bi = reader.read(0, param);
        File file = new File(dstFile);
        ImageIO.write(bi, reader.getFormatName(), file);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.shending.support.CompressPic.java

/**
 * ?//from  w w  w .  j  a  va2 s.c  o m
 *
 * @param srcFile
 * @param dstFile
 * @param widthRange
 * @param heightRange
 */
public static void cutSquare(String srcFile, String dstFile, int widthRange, int heightRange, int width,
        int height) {
    int x = 0;
    int y = 0;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new File(srcFile));
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        ImageReader reader = (ImageReader) iterator.next();
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        int oldWidth = reader.getWidth(0);
        int oldHeight = reader.getHeight(0);
        int newWidth, newHeight;
        if (width <= oldWidth && height <= oldHeight) {
            newWidth = oldHeight * widthRange / heightRange;
            if (newWidth < oldWidth) {
                newHeight = oldHeight;
                x = (oldWidth - newWidth) / 2;
            } else {
                newWidth = oldWidth;
                newHeight = oldWidth * heightRange / widthRange;
                y = (oldHeight - newHeight) / 2;
            }
            Rectangle rectangle = new Rectangle(x, y, newWidth, newHeight);
            param.setSourceRegion(rectangle);
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bi.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        } else {
            BufferedImage bi = reader.read(0, param);
            BufferedImage tag = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = tag.createGraphics();
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, tag.getWidth(), tag.getHeight());
            g2d.drawImage(bi.getScaledInstance(bi.getWidth(), bi.getHeight(), Image.SCALE_SMOOTH),
                    (width - bi.getWidth()) / 2, (height - bi.getHeight()) / 2, null);
            g2d.dispose();
            File file = new File(dstFile);
            ImageIO.write(tag, reader.getFormatName(), file);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jimcat.services.imagemanager.ImageUtil.java

/**
 * this methode will load given image using a subsample rate
 * //  w  w w . j a va2 s  .c  om
 * this strategie is just reading a subset of images lines ans rowes to
 * reduce memory usage and cpu time.
 * 
 * @param reader -
 *            the reader to load image from
 * @param size -
 *            the resulting image size
 * @param quality -
 *            the quality used for necessary rendering
 * @return the image as buffered image
 * @throws IOException
 */
private static BufferedImage loadImageWithSubSampling(ImageReader reader, Dimension size, ImageQuality quality)
        throws IOException {

    // prepaire image reader parameter
    ImageReadParam param = reader.getDefaultReadParam();

    // calculate subsampling values
    int width = reader.getWidth(0);
    int height = reader.getHeight(0);
    int rateX = width / size.width;
    int rateY = height / size.height;
    param.setSourceSubsampling(rateX, rateY, 0, 0);

    // load image with subsamples
    BufferedImage img = reader.read(0, param);

    // scale to final size
    BufferedImage result = getScaledInstance(img, size, quality);

    // return result
    return result;
}

From source file:org.carcv.core.model.file.FileCarImage.java

/**
 * Reads a rectangular region from an image in the inStream.
 *
 * @param inStream the InputStream from which to load the image fraction
 * @param rect specifies the rectangular region to load as the image
 * @throws IOException if an error during loading occurs
 *///from w w w . j  a  va2s  .  com
public void loadFragment(InputStream inStream, Rectangle rect) throws IOException {
    ImageInputStream imageStream = ImageIO.createImageInputStream(inStream);
    ImageReader reader = ImageIO.getImageReaders(imageStream).next();
    ImageReadParam param = reader.getDefaultReadParam();

    param.setSourceRegion(rect);
    reader.setInput(imageStream, true, true);

    this.image = reader.read(0, param);

    reader.dispose();
    imageStream.close();
}

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
@Nonnull/*  ww w  .  ja  va  2 s  .c o  m*/
@Deprecated
protected BufferedImage assertLoadImage(final @Nonnull ImageReader ir,
        final @CheckForNull RAWImageReadParam readParam, final @Nonnegative int width,
        final @Nonnegative int height, final @Nonnegative int bandCount, final @Nonnegative int sampleSize)
        throws IOException {
    final BufferedImage image = ir.read(0, readParam);
    assertNotNull(image);
    final Dimension imageSize = new Dimension(image.getWidth(), image.getHeight());
    final Dimension expectedSize = new Dimension(width, height);
    assertEquals("loaded image size: ", expectedSize, imageSize);
    assertEquals("loaded image band count", bandCount, image.getData().getNumBands());

    for (int i = 0; i < bandCount; i++) {
        assertEquals("loaded image sample size for band " + i, sampleSize,
                image.getData().getSampleModel().getSampleSize(i));
    }

    return image;
}

From source file:it.tidalwave.imageio.test.ImageReaderTestSupport.java

/*******************************************************************************************************************
 * /*from   ww  w .  ja  va2  s  .  c om*/
 * 
 ******************************************************************************************************************/
@Nonnull
protected BufferedImage assertLoadImage(final @Nonnull ImageReader ir,
        final @CheckForNull RAWImageReadParam readParam, final @Nonnegative int width,
        final @Nonnegative int height, final @Nonnegative int bandCount, final @Nonnegative int sampleSize,
        final int type) throws IOException {
    final BufferedImage image = ir.read(0, readParam);
    assertNotNull(image);
    final Dimension imageSize = new Dimension(image.getWidth(), image.getHeight());
    final Dimension expectedSize = new Dimension(width, height);
    assertEquals("loaded image size: ", expectedSize, imageSize);
    assertEquals("loaded image band count", bandCount, image.getData().getNumBands());
    assertEquals(type, image.getType());

    for (int i = 0; i < bandCount; i++) {
        assertEquals("loaded image sample size for band " + i, sampleSize,
                image.getData().getSampleModel().getSampleSize(i));
    }

    return image;
}

From source file:org.olat.core.commons.services.image.spi.ImageHelperImpl.java

private static SizeAndBufferedImage getImage(ImageInputStream stream, String suffix) {
    Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
    if (iter.hasNext()) {
        ImageReader reader = iter.next();
        try {/*w  w w .  j  a v  a2s.  c om*/
            reader.setInput(stream, true, true);
            int width = reader.getWidth(reader.getMinIndex());
            int height = reader.getHeight(reader.getMinIndex());
            Size size = new Size(width, height, false);
            SizeAndBufferedImage all = new SizeAndBufferedImage(size, null);

            int readerMinIndex = reader.getMinIndex();
            ImageReadParam param = reader.getDefaultReadParam();
            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
            while (imageTypes.hasNext()) {
                try {
                    ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                    int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                    if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                        param.setDestinationType(imageTypeSpecifier);
                    }
                    all.setImage(reader.read(readerMinIndex, param));
                    return all;
                } catch (IllegalArgumentException e) {
                    log.warn(e.getMessage(), e);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            reader.dispose();
        }
    } else {
        log.error("No reader found for given format: " + suffix, null);
    }
    return null;
}

From source file:nitf.imageio.NITFReader.java

/**
 * Optimization to read the entire image in one fell swoop... This is most
 * likely the common use case for this codec, so we hope this optimization
 * will be helpful./*from   w w  w  .jav  a2 s .  co m*/
 * 
 * @param imageIndex
 * @param sourceXSubsampling
 * @param sourceYSubsampling
 * @param bandOffsets
 * @param pixelSize
 * @param imRas
 * @throws IOException
 */
protected void readFullImage(int imageIndex, Rectangle destRegion, int sourceXSubsampling,
        int sourceYSubsampling, int[] bandOffsets, int pixelSize, WritableRaster imRas) throws IOException {
    try {
        ImageSubheader subheader = record.getImages()[imageIndex].getSubheader();
        int numCols = destRegion.width;
        int numRows = destRegion.height;

        int nBands = subheader.getBandCount();

        /*
         * NOTE: This is a "fix" that will be removed once the underlying
         * NITRO library gets patched. Currently, if you make a request of a
         * single band, it doesn't matter which band you request - the data
         * from the first band will be returned regardless. This is
         * obviously wrong. To thwart this, we will read all bands, then
         * scale down what we return to the user based on their actual
         * request.
         */

        int[] requestBands = bandOffsets;
        /*
         * if (nBands != bandOffsets.length && bandOffsets.length == 1
         * && bandOffsets[0] != 0)
         * {
         * requestBands = new int[nBands];
         * for (int i = 0; i < nBands; ++i)
         * requestBands[i] = i;
         * }
         */

        int bufSize = numCols * numRows * pixelSize;
        byte[][] imageBuf = new byte[requestBands.length][bufSize];

        // make a SubWindow from the params
        // TODO may want to read by blocks or rows to make faster and more
        // memory efficient
        SubWindow window;
        window = new SubWindow();
        window.setNumBands(requestBands.length);
        window.setBandList(requestBands);
        window.setNumCols(numCols);
        window.setNumRows(numRows);
        window.setStartCol(0);
        window.setStartRow(0);

        // the NITRO library can do the subsampling for us
        if (sourceYSubsampling != 1 || sourceXSubsampling != 1) {
            DownSampler downSampler = new PixelSkipDownSampler(sourceYSubsampling, sourceXSubsampling);
            window.setDownSampler(downSampler);
        }

        // String pixelJustification = subheader.getPixelJustification()
        // .getStringData().trim();
        // boolean shouldSwap = pixelJustification.equals("R");

        // since this is Java, we need the data in big-endian format
        // boolean shouldSwap = ByteOrder.nativeOrder() !=
        // ByteOrder.BIG_ENDIAN;

        nitf.ImageReader imageReader = getImageReader(imageIndex);
        imageReader.read(window, imageBuf);

        List<ByteBuffer> bandBufs = new ArrayList<ByteBuffer>();

        for (int i = 0; i < bandOffsets.length; ++i) {
            ByteBuffer bandBuf = null;

            // the special "fix" we added needs to do this
            if (bandOffsets.length != requestBands.length) {
                bandBuf = ByteBuffer.wrap(imageBuf[bandOffsets[i]]);
            } else {
                bandBuf = ByteBuffer.wrap(imageBuf[i]);
            }
            // ban dBuf.order(ByteOrder.nativeOrder());
            // shouldSwap ? ByteOrder.LITTLE_ENDIAN
            // : ByteOrder.BIG_ENDIAN);

            bandBufs.add(bandBuf);
        }

        // optimization for 1 band case... just dump the whole thing
        if (bandOffsets.length == 1) {
            ByteBuffer bandBuf = bandBufs.get(0);

            switch (pixelSize) {
            case 1:
                ByteBuffer rasterByteBuf = ByteBuffer.wrap(((DataBufferByte) imRas.getDataBuffer()).getData());
                rasterByteBuf.put(bandBuf);
                break;
            case 2:
                ShortBuffer rasterShortBuf = ShortBuffer
                        .wrap(((DataBufferUShort) imRas.getDataBuffer()).getData());
                rasterShortBuf.put(bandBuf.asShortBuffer());
                break;
            case 4:
                FloatBuffer rasterFloatBuf = FloatBuffer
                        .wrap(((DataBufferFloat) imRas.getDataBuffer()).getData());
                rasterFloatBuf.put(bandBuf.asFloatBuffer());
                break;
            case 8:
                DoubleBuffer rasterDoubleBuf = DoubleBuffer
                        .wrap(((DataBufferDouble) imRas.getDataBuffer()).getData());
                rasterDoubleBuf.put(bandBuf.asDoubleBuffer());
                break;
            }
        } else {
            // for multi-band case, we need to iterate over each pixel...
            // TODO -- optimize this!... somehow

            for (int srcY = 0, srcX = 0; srcY < numRows; srcY++) {
                // Copy each (subsampled) source pixel into imRas
                for (int dstX = 0; dstX < numCols; srcX += pixelSize, dstX++) {
                    for (int i = 0; i < bandOffsets.length; ++i) {
                        ByteBuffer bandBuf = bandBufs.get(i);

                        switch (pixelSize) {
                        case 1:
                            imRas.setSample(dstX, srcY, i, bandBuf.get(srcX));
                            break;
                        case 2:
                            imRas.setSample(dstX, srcY, i, bandBuf.getShort(srcX));
                            break;
                        case 4:
                            imRas.setSample(dstX, srcY, i, bandBuf.getFloat(srcX));
                            break;
                        case 8:
                            imRas.setSample(dstX, srcY, i, bandBuf.getDouble(srcX));
                            break;
                        }
                    }
                }
            }
        }
    } catch (NITFException e1) {
        throw new IOException(ExceptionUtils.getStackTrace(e1));
    }
}