Search in sources :

Example 16 with ImageReadParam

use of javax.imageio.ImageReadParam in project jdk8u_jdk by JetBrains.

the class PngOutputTypeTest method doTest.

public void doTest() throws IOException {
    /*
         * This test verifies that png images with color type RGB or RGBA
         * are decoded as buffered  image of some standard type.
         *
         * So we need to be sure that image provided by
         * user has required color type - RGB or RGBA
         */
    if (!checkImageType()) {
        System.out.println("Test IGNORED!");
        return;
    }
    def = reader.read(0);
    System.out.println("Default image type: " + def.getType());
    if (def == null || def.getType() == BufferedImage.TYPE_CUSTOM) {
        throw new RuntimeException("Test FAILED!");
    }
    raw_type = reader.getRawImageType(0);
    ImageReadParam param = reader.getDefaultReadParam();
    param.setDestinationType(raw_type);
    System.out.println("Reading with raw image type...");
    raw = reader.read(0, param);
    System.out.println("Type of raw image is " + raw.getType());
    compare(def, raw);
    Iterator<ImageTypeSpecifier> types = reader.getImageTypes(0);
    while (types.hasNext()) {
        ImageTypeSpecifier t = types.next();
        System.out.println("Test type: " + t);
        param.setDestinationType(t);
        BufferedImage img = reader.read(0, param);
        System.out.println("Result type: " + img.getType());
        compare(def, img);
        System.out.println("Done.\n");
    }
    System.out.println("Test PASSED.");
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) BufferedImage(java.awt.image.BufferedImage)

Example 17 with ImageReadParam

use of javax.imageio.ImageReadParam in project jdk8u_jdk by JetBrains.

the class BMPImageReader method readEmbedded.

/** Decodes the jpeg/png image embedded in the bitmap using any jpeg
     *  ImageIO-style plugin.
     *
     * @param bi The destination <code>BufferedImage</code>.
     * @param bmpParam The <code>ImageReadParam</code> for decoding this
     *          BMP image.  The parameters for subregion, band selection and
     *          subsampling are used in decoding the jpeg image.
     */
private BufferedImage readEmbedded(int type, BufferedImage bi, ImageReadParam bmpParam) throws IOException {
    String format;
    switch(type) {
        case BI_JPEG:
            format = "JPEG";
            break;
        case BI_PNG:
            format = "PNG";
            break;
        default:
            throw new IOException("Unexpected compression type: " + type);
    }
    ImageReader reader = ImageIO.getImageReadersByFormatName(format).next();
    if (reader == null) {
        throw new RuntimeException(I18N.getString("BMPImageReader4") + " " + format);
    }
    // prepare input
    byte[] buff = new byte[(int) imageSize];
    iis.read(buff);
    reader.setInput(ImageIO.createImageInputStream(new ByteArrayInputStream(buff)));
    if (bi == null) {
        ImageTypeSpecifier embType = reader.getImageTypes(0).next();
        bi = embType.createBufferedImage(destinationRegion.x + destinationRegion.width, destinationRegion.y + destinationRegion.height);
    }
    reader.addIIOReadProgressListener(new EmbeddedProgressAdapter() {

        public void imageProgress(ImageReader source, float percentageDone) {
            processImageProgress(percentageDone);
        }
    });
    reader.addIIOReadUpdateListener(new IIOReadUpdateListener() {

        public void imageUpdate(ImageReader source, BufferedImage theImage, int minX, int minY, int width, int height, int periodX, int periodY, int[] bands) {
            processImageUpdate(theImage, minX, minY, width, height, periodX, periodY, bands);
        }

        public void passComplete(ImageReader source, BufferedImage theImage) {
            processPassComplete(theImage);
        }

        public void passStarted(ImageReader source, BufferedImage theImage, int pass, int minPass, int maxPass, int minX, int minY, int periodX, int periodY, int[] bands) {
            processPassStarted(theImage, pass, minPass, maxPass, minX, minY, periodX, periodY, bands);
        }

        public void thumbnailPassComplete(ImageReader source, BufferedImage thumb) {
        }

        public void thumbnailPassStarted(ImageReader source, BufferedImage thumb, int pass, int minPass, int maxPass, int minX, int minY, int periodX, int periodY, int[] bands) {
        }

        public void thumbnailUpdate(ImageReader source, BufferedImage theThumbnail, int minX, int minY, int width, int height, int periodX, int periodY, int[] bands) {
        }
    });
    reader.addIIOReadWarningListener(new IIOReadWarningListener() {

        public void warningOccurred(ImageReader source, String warning) {
            processWarningOccurred(warning);
        }
    });
    ImageReadParam param = reader.getDefaultReadParam();
    param.setDestination(bi);
    param.setDestinationBands(bmpParam.getDestinationBands());
    param.setDestinationOffset(bmpParam.getDestinationOffset());
    param.setSourceBands(bmpParam.getSourceBands());
    param.setSourceRegion(bmpParam.getSourceRegion());
    param.setSourceSubsampling(bmpParam.getSourceXSubsampling(), bmpParam.getSourceYSubsampling(), bmpParam.getSubsamplingXOffset(), bmpParam.getSubsamplingYOffset());
    reader.read(0, param);
    return bi;
}
Also used : IIOReadWarningListener(javax.imageio.event.IIOReadWarningListener) IIOException(javax.imageio.IIOException) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) BufferedImage(java.awt.image.BufferedImage) Point(java.awt.Point) IIOReadUpdateListener(javax.imageio.event.IIOReadUpdateListener) ImageReadParam(javax.imageio.ImageReadParam) ImageReader(javax.imageio.ImageReader)

Example 18 with ImageReadParam

use of javax.imageio.ImageReadParam in project fess by codelibs.

the class WebDriverGenerator method convert.

protected void convert(final File inputFile, final File outputFile) {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    try (ImageInputStream input = ImageIO.createImageInputStream(inputFile)) {
        final Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
        if (readers.hasNext()) {
            final ImageReader reader = readers.next();
            try {
                reader.setInput(input);
                final ImageReadParam param = reader.getDefaultReadParam();
                final int samplingWidth = reader.getWidth(0) / fessConfig.getThumbnailHtmlPhantomjsThumbnailWidthAsInteger();
                final int samplingHeight = reader.getHeight(0) / fessConfig.getThumbnailHtmlPhantomjsThumbnailHeightAsInteger();
                param.setSourceSubsampling(samplingWidth, samplingHeight, 0, 0);
                param.setSourceRegion(new Rectangle(fessConfig.getThumbnailHtmlPhantomjsWindowWidthAsInteger(), fessConfig.getThumbnailHtmlPhantomjsThumbnailHeightAsInteger() * reader.getHeight(0) / fessConfig.getThumbnailHtmlPhantomjsThumbnailWidthAsInteger()));
                final BufferedImage image = reader.read(0, param);
                ImageIO.write(image, fessConfig.getThumbnailHtmlPhantomjsFormat(), outputFile);
                image.flush();
            } finally {
                reader.dispose();
            }
        }
    } catch (final Throwable t) {
        logger.warn("Failed to convert " + inputFile.getAbsolutePath(), t);
        inputFile.renameTo(outputFile);
    }
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) ImageInputStream(javax.imageio.stream.ImageInputStream) Rectangle(java.awt.Rectangle) ImageReader(javax.imageio.ImageReader) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) BufferedImage(java.awt.image.BufferedImage)

Example 19 with ImageReadParam

use of javax.imageio.ImageReadParam in project fess by codelibs.

the class HtmlTagBasedGenerator method saveImage.

protected boolean saveImage(final ImageInputStream input, final File outputFile) throws IOException {
    final FessConfig fessConfig = ComponentUtil.getFessConfig();
    final Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
    if (readers.hasNext()) {
        final ImageReader reader = readers.next();
        try {
            reader.setInput(input);
            final ImageReadParam param = reader.getDefaultReadParam();
            final int width = reader.getWidth(0);
            final int height = reader.getHeight(0);
            final int samplingWidth = width / fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger();
            final int samplingHeight = height / fessConfig.getThumbnailHtmlImageThumbnailHeightAsInteger();
            param.setSourceSubsampling(samplingWidth <= 0 ? 1 : samplingWidth, samplingHeight <= 0 ? 1 : samplingHeight, 0, 0);
            param.setSourceRegion(new Rectangle(width, height > width ? width : height));
            final BufferedImage image = reader.read(0, param);
            final int thumbnailWidth = fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger();
            final int thumbnailHeight = (int) (((float) (height > width ? width : height)) * fessConfig.getThumbnailHtmlImageThumbnailWidthAsInteger().floatValue() / (float) width);
            BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, image.getType());
            thumbnail.getGraphics().drawImage(image.getScaledInstance(thumbnailWidth, thumbnailHeight, Image.SCALE_AREA_AVERAGING), 0, 0, thumbnailWidth, thumbnailHeight, null);
            ImageIO.write(thumbnail, fessConfig.getThumbnailHtmlImageFormat(), outputFile);
            image.flush();
            return true;
        } finally {
            reader.dispose();
        }
    }
    return false;
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) Rectangle(java.awt.Rectangle) ImageReader(javax.imageio.ImageReader) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) BufferedImage(java.awt.image.BufferedImage)

Example 20 with ImageReadParam

use of javax.imageio.ImageReadParam in project poi by apache.

the class BitmapImageRenderer method readImage.

/**
     * Read the image data via ImageIO and optionally try to workaround metadata errors.
     * The resulting image is of image type {@link BufferedImage#TYPE_INT_ARGB}
     *
     * @param data the data stream
     * @param contentType the content type
     * @return the bufferedImage or null, if there was no image reader for this content type
     * @throws IOException thrown if there was an error while processing the image
     */
private static BufferedImage readImage(InputStream data, String contentType) throws IOException {
    IOException lastException = null;
    BufferedImage img = null;
    if (data.markSupported()) {
        data.mark(data.available());
    }
    // currently don't use FileCacheImageInputStream,
    // because of the risk of filling the file handles (see #59166)
    ImageInputStream iis = new MemoryCacheImageInputStream(data);
    try {
        iis = new MemoryCacheImageInputStream(data);
        iis.mark();
        Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
        while (img == null && iter.hasNext()) {
            ImageReader reader = iter.next();
            ImageReadParam param = reader.getDefaultReadParam();
            // 0:default mode, 1:fallback mode
            for (int mode = 0; img == null && mode < 3; mode++) {
                lastException = null;
                try {
                    iis.reset();
                } catch (IOException e) {
                    if (data.markSupported()) {
                        data.reset();
                        data.mark(data.available());
                        iis.close();
                        iis = new MemoryCacheImageInputStream(data);
                    } else {
                        // can't restore the input stream, so we need to stop processing here
                        lastException = e;
                        break;
                    }
                }
                iis.mark();
                try {
                    switch(mode) {
                        case 0:
                            reader.setInput(iis, false, true);
                            img = reader.read(0, param);
                            break;
                        case 1:
                            {
                                // try to load picture in gray scale mode
                                // fallback mode for invalid image band metadata
                                // see http://stackoverflow.com/questions/10416378
                                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;
                                    }
                                }
                                reader.setInput(iis, false, true);
                                img = reader.read(0, param);
                                break;
                            }
                        case 2:
                            {
                                // try to load truncated pictures by supplying a BufferedImage
                                // and use the processed data up till the point of error
                                reader.setInput(iis, false, true);
                                int height = reader.getHeight(0);
                                int width = reader.getWidth(0);
                                Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
                                if (imageTypes.hasNext()) {
                                    ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
                                    img = imageTypeSpecifier.createBufferedImage(width, height);
                                    param.setDestination(img);
                                } else {
                                    lastException = new IOException("unable to load even a truncated version of the image.");
                                    break;
                                }
                                try {
                                    reader.read(0, param);
                                } finally {
                                    if (img.getType() != BufferedImage.TYPE_INT_ARGB) {
                                        int y = findTruncatedBlackBox(img, width, height);
                                        if (y < height) {
                                            BufferedImage argbImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                                            Graphics2D g = argbImg.createGraphics();
                                            g.clipRect(0, 0, width, y);
                                            g.drawImage(img, 0, 0, null);
                                            g.dispose();
                                            img.flush();
                                            img = argbImg;
                                        }
                                    }
                                }
                                break;
                            }
                    }
                } catch (IOException e) {
                    if (mode < 2) {
                        lastException = e;
                    }
                } catch (RuntimeException e) {
                    if (mode < 2) {
                        lastException = new IOException("ImageIO runtime exception - " + (mode == 0 ? "normal" : "fallback"), e);
                    }
                }
            }
            reader.dispose();
        }
    } finally {
        iis.close();
    }
    // If you don't have an image at the end of all readers
    if (img == null) {
        if (lastException != null) {
            // multiple locations above ...
            throw lastException;
        }
        LOG.log(POILogger.WARN, "Content-type: " + contentType + " is not support. Image ignored.");
        return null;
    }
    // add alpha channel
    if (img.getType() != BufferedImage.TYPE_INT_ARGB) {
        BufferedImage argbImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = argbImg.getGraphics();
        g.drawImage(img, 0, 0, null);
        g.dispose();
        return argbImg;
    }
    return img;
}
Also used : ImageInputStream(javax.imageio.stream.ImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) Graphics2D(java.awt.Graphics2D) Graphics(java.awt.Graphics) ImageReadParam(javax.imageio.ImageReadParam) Iterator(java.util.Iterator) ImageReader(javax.imageio.ImageReader)

Aggregations

ImageReadParam (javax.imageio.ImageReadParam)20 BufferedImage (java.awt.image.BufferedImage)16 ImageReader (javax.imageio.ImageReader)14 IOException (java.io.IOException)9 ImageInputStream (javax.imageio.stream.ImageInputStream)6 MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 InputStream (java.io.InputStream)5 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)5 MediaType (org.springframework.http.MediaType)4 Graphics2D (java.awt.Graphics2D)3 Iterator (java.util.Iterator)3 UnavailableException (javax.servlet.UnavailableException)3 HttpHeaders (org.springframework.http.HttpHeaders)3 ResponseEntity (org.springframework.http.ResponseEntity)3 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 Rectangle (java.awt.Rectangle)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ImageWriter (javax.imageio.ImageWriter)2