Example usage for javax.imageio ImageReader getDefaultReadParam

List of usage examples for javax.imageio ImageReader getDefaultReadParam

Introduction

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

Prototype

public ImageReadParam getDefaultReadParam() 

Source Link

Document

Returns a default ImageReadParam object appropriate for this format.

Usage

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  ava  2 s  .c o m*/
            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:org.photovault.image.ImageIOImage.java

/**
 Load the image and/or metadata//  w  ww .  j  av a 2 s . c o m
 @param loadImage Load the image pixel data if <CODE>true</CODE>
 @param loadMetadata Load image metadata if <CODE>true</CODE>.
 @param minWidth Minimum width of the loaded image
 @param minHeight Minimum height of the loaded image
 @param isLowQualityAllowed If <code>true</code>, use larger subsampling 
 to speed up loading.
 */
private void load(boolean loadImage, boolean loadMetadata, int minWidth, int minHeight,
        boolean isLowQualityAllowed) {
    if (f != null && f.canRead()) {
        ImageReader reader = getImageReader(f);
        if (reader != null) {
            log.debug("Creating stream");
            ImageInputStream iis = null;
            try {
                iis = ImageIO.createImageInputStream(f);
                reader.setInput(iis, false, false);
                width = reader.getWidth(0);
                height = reader.getHeight(0);
                if (loadImage) {
                    RenderedImage ri = null;
                    if (isLowQualityAllowed) {
                        ri = readExifThumbnail(f);
                        if (ri == null || !isOkForThumbCreation(ri.getWidth(), ri.getHeight(), minWidth,
                                minHeight, reader.getAspectRatio(0), 0.01)) {
                            /*
                             EXIF thumbnail either did not exist or was unusable,
                             try to read subsampled version of original
                             */
                            ri = readSubsampled(reader, minWidth, minHeight);
                        }
                    } else {
                        /*
                         High quality image is requested.
                                 
                         If the image is very large, use subsampling anyway
                         to decrease memory consumption & speed up interactive 
                         operations. Anyway, most often user just views image 
                         at screen resolution
                         */
                        ImageReadParam param = reader.getDefaultReadParam();

                        if (minWidth * 2 < width && minHeight * 2 < height) {
                            param.setSourceSubsampling(2, 2, 0, 0);
                        }
                        ri = reader.read(0, param);

                    }
                    if (ri != null) {
                        /*
                         TODO: JAI seems to have problems in doing convolutions
                         for large image tiles. Split image to reasonably sized
                         tiles as a workaround for this.
                         */
                        ri = new TiledImage(ri, 256, 256);
                        image = new RenderedImageAdapter(ri);
                        originalSampleModel = image.getSampleModel();
                        originalColorModel = image.getColorModel();
                        final float[] DEFAULT_KERNEL_1D = { 0.25f, 0.5f, 0.25f };
                        ParameterBlock pb = new ParameterBlock();
                        KernelJAI kernel = new KernelJAI(DEFAULT_KERNEL_1D.length, DEFAULT_KERNEL_1D.length,
                                DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D.length / 2, DEFAULT_KERNEL_1D,
                                DEFAULT_KERNEL_1D);
                        pb.add(kernel);
                        BorderExtender extender = BorderExtender.createInstance(BorderExtender.BORDER_COPY);
                        RenderingHints hints = JAI.getDefaultInstance().getRenderingHints();
                        if (hints == null) {
                            hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
                        } else {
                            hints.put(JAI.KEY_BORDER_EXTENDER, extender);
                        }

                        RenderedOp filter = new RenderedOp("convolve", pb, hints);
                        // javax.media.jai.operator.BoxFilterDescriptor.create( null, new Integer(2), new Integer(2), new Integer(0), new Integer(0), null );

                        // Add the subsampling operation.
                        pb = new ParameterBlock();
                        pb.addSource(filter);
                        pb.add(new Float(0.5F)).add(new Float(0.5F));
                        pb.add(new Float(0.0F)).add(new Float(0.0F));
                        pb.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
                        RenderedOp downSampler = new RenderedOp("scale", pb, null);

                        renderableImage = RenderableDescriptor.createRenderable(image, downSampler, null, null,
                                null, null, null);
                    } else {
                        image = null;
                        renderableImage = null;
                    }
                    imageIsLowQuality = isLowQualityAllowed;
                }
                if (loadMetadata) {
                    readImageMetadata(reader);
                }
            } catch (Exception ex) {
                log.warn(ex.getMessage());
                ex.printStackTrace();
                return;
            }
        }
    }
}

From source file:org.photovault.image.ImageIOImage.java

/**
 Read the image (either original or proper thumbnail in the same file and subsample 
 it to save memory & time. The image is subsampled so that its reasolution is the
 smallest possible that is bigger than given limits. 
         //from  w ww .  j ava  2 s.co m
 @param reader The image reader that is used for reading the image
 @param minWidth Minimum width of the subsampled image
 @param minHeight Minimum height of the subsampled iamge
         
 @return Subsampled image.
 */

private RenderedImage readSubsampled(ImageReader reader, int minWidth, int minHeight) throws IOException {
    /*
     We try to ensure that the thumbnail is actually from the original image
     by comparing aspect ratio of it to original. This is not a perfect check
     but it will usually catch the most typical errors (like having a the original
     rotated by RAW conversion SW but still the original EXIF thumbnail.
     */
    double origAspect = reader.getAspectRatio(0);
    double aspectAccuracy = 0.01;
    int minInstanceSide = Math.max(minWidth, minHeight);

    int numThumbs = 0;
    RenderedImage image = null;
    try {
        int numImages = reader.getNumImages(true);
        if (numImages > 0) {
            numThumbs = reader.getNumThumbnails(0);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    if (numThumbs > 0 && isOkForThumbCreation(reader.getThumbnailWidth(0, 0), reader.getThumbnailHeight(0, 0),
            minWidth, minHeight, origAspect, aspectAccuracy)) {
        // There is a thumbanil that is big enough - use it

        log.debug("Original has thumbnail, size " + reader.getThumbnailWidth(0, 0) + " x "
                + reader.getThumbnailHeight(0, 0));
        image = reader.readThumbnail(0, 0);
        log.debug("Read thumbnail");
    } else {
        log.debug("No thumbnail in original");
        ImageReadParam param = reader.getDefaultReadParam();

        // Find the maximum subsampling rate we can still use for creating
        // a quality thumbnail. Some image format readers seem to have
        // problems with subsampling values (e.g. PNG sometimes crashed
        // the whole virtual machine, to for now let's do this only
        // with JPG.
        int subsampling = 1;
        if (reader.getFormatName().equals("JPEG")) {
            int minDim = Math.min(reader.getWidth(0), reader.getHeight(0));
            while (2 * minInstanceSide * subsampling < minDim) {
                subsampling *= 2;
            }
        }
        param.setSourceSubsampling(subsampling, subsampling, 0, 0);
        image = reader.read(0, param);
    }
    return image;
}

From source file:org.psystems.dicom.daemon.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);/*w  w  w  .j  a  v  a 2  s  .c o  m*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    OutputStream out = null;
    try {
        reader.setInput(iis, false);
        if (reader.getNumImages(false) <= 0) {
            System.out.println("\nError: " + src + " - Don't haven any images!");
            return;
        }
        //            System.out.println("!!! frame="+frame+" p="+reader.getNumImages(false));
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        out = new BufferedOutputStream(new FileOutputStream(dest));
        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
        enc.encode(bi);
    } finally {
        CloseUtils.safeClose(iis);
        CloseUtils.safeClose(out);
    }
    System.out.print('.');
}

From source file:org.psystems.dicomweb.Dcm2Jpg.java

public void convert(File src, File dest) throws IOException {
    Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");
    ImageReader reader = iter.next();
    DicomImageReadParam param = (DicomImageReadParam) reader.getDefaultReadParam();
    param.setWindowCenter(center);/*from w  w  w .j a v  a 2s. c  o  m*/
    param.setWindowWidth(width);
    param.setVoiLutFunction(vlutFct);
    param.setPresentationState(prState);
    param.setPValue2Gray(pval2gray);
    param.setAutoWindowing(autoWindowing);
    ImageInputStream iis = ImageIO.createImageInputStream(src);
    BufferedImage bi;
    OutputStream out = null;
    try {
        reader.setInput(iis, false);
        bi = reader.read(frame - 1, param);
        if (bi == null) {
            System.out.println("\nError: " + src + " - couldn't read!");
            return;
        }
        out = new BufferedOutputStream(new FileOutputStream(dest));
        JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(out);
        enc.encode(bi);
    } finally {
        CloseUtils.safeClose(iis);
        CloseUtils.safeClose(out);
    }
    System.out.print('.');
}

From source file:sernet.verinice.service.commands.LoadAttachmentFile.java

private BufferedImage readImageFromByteArrayFallback() throws IOException {
    ImageInputStream in = ImageIO
            .createImageInputStream(new ByteArrayInputStream(getAttachmentFile().getFileData()));
    Iterator<ImageReader> iter = ImageIO.getImageReaders(in);
    BufferedImage image = null;/*from ww w . j  ava  2 s . c  om*/

    while (iter.hasNext()) {
        ImageReader reader = null;
        try {
            reader = (ImageReader) iter.next();
            ImageReadParam param = reader.getDefaultReadParam();
            reader.setInput(in, true, true);
            Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
            while (imageTypes.hasNext()) {
                ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
                if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
                    param.setDestinationType(imageTypeSpecifier);
                    break;
                }
            }
            image = reader.read(0, param);
            if (null != image) {
                break;
            }
        } catch (Exception e) {
            getLog().error("Error while reading image the advanced way. DbId: " + getAttachmentFile().getDbId(),
                    e);
        } finally {
            if (null != reader) {
                reader.dispose();
            }
        }

    }
    return image;
}