Search in sources :

Example 26 with MemoryCacheImageInputStream

use of javax.imageio.stream.MemoryCacheImageInputStream in project pdfbox by apache.

the class JPXFilter method readJPX.

// try to read using JAI Image I/O
private BufferedImage readJPX(InputStream input, DecodeOptions options, DecodeResult result) throws IOException {
    ImageReader reader = findImageReader("JPEG2000", "Java Advanced Imaging (JAI) Image I/O Tools are not installed");
    // PDFBOX-4121: ImageIO.createImageInputStream() is much slower
    try (ImageInputStream iis = new MemoryCacheImageInputStream(input)) {
        reader.setInput(iis, true, true);
        ImageReadParam irp = reader.getDefaultReadParam();
        irp.setSourceRegion(options.getSourceRegion());
        irp.setSourceSubsampling(options.getSubsamplingX(), options.getSubsamplingY(), options.getSubsamplingOffsetX(), options.getSubsamplingOffsetY());
        options.setFilterSubsampled(true);
        BufferedImage image;
        try {
            image = reader.read(0, irp);
        } catch (Exception e) {
            // wrap and rethrow any exceptions
            throw new IOException("Could not read JPEG 2000 (JPX) image", e);
        }
        COSDictionary parameters = result.getParameters();
        // "If the image stream uses the JPXDecode filter, this entry is optional
        // and shall be ignored if present"
        // 
        // note that indexed color spaces make the BPC logic tricky, see PDFBOX-2204
        int bpc = image.getColorModel().getPixelSize() / image.getRaster().getNumBands();
        parameters.setInt(COSName.BITS_PER_COMPONENT, bpc);
        // "Decode shall be ignored, except in the case where the image is treated as a mask"
        if (!parameters.getBoolean(COSName.IMAGE_MASK, false)) {
            parameters.setItem(COSName.DECODE, null);
        }
        // override dimensions, see PDFBOX-1735
        parameters.setInt(COSName.WIDTH, reader.getWidth(0));
        parameters.setInt(COSName.HEIGHT, reader.getHeight(0));
        // extract embedded color space
        if (!parameters.containsKey(COSName.COLORSPACE)) {
            if (image.getSampleModel() instanceof MultiPixelPackedSampleModel && image.getColorModel().getPixelSize() == 1 && image.getRaster().getNumBands() == 1 && image.getColorModel() instanceof IndexColorModel) {
                // PDFBOX-4326:
                // force CS_GRAY colorspace because colorspace in IndexColorModel
                // has 3 colors despite that there is only 1 color per pixel
                // in raster
                result.setColorSpace(new PDJPXColorSpace(ColorSpace.getInstance(ColorSpace.CS_GRAY)));
            } else {
                result.setColorSpace(new PDJPXColorSpace(image.getColorModel().getColorSpace()));
            }
        }
        return image;
    } finally {
        reader.dispose();
    }
}
Also used : PDJPXColorSpace(org.apache.pdfbox.pdmodel.graphics.color.PDJPXColorSpace) ImageReadParam(javax.imageio.ImageReadParam) COSDictionary(org.apache.pdfbox.cos.COSDictionary) ImageInputStream(javax.imageio.stream.ImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MultiPixelPackedSampleModel(java.awt.image.MultiPixelPackedSampleModel) IOException(java.io.IOException) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) IndexColorModel(java.awt.image.IndexColorModel)

Example 27 with MemoryCacheImageInputStream

use of javax.imageio.stream.MemoryCacheImageInputStream in project pdfbox by apache.

the class PNGConverter method buildTransparencyMaskFromIndexedData.

private static PDImageXObject buildTransparencyMaskFromIndexedData(PDDocument doc, PDImageXObject image, PNGConverterState state) throws IOException {
    Filter flateDecode = FilterFactory.INSTANCE.getFilter(COSName.FLATE_DECODE);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    COSDictionary decodeParams = buildDecodeParams(state, PDDeviceGray.INSTANCE);
    COSDictionary imageDict = new COSDictionary();
    imageDict.setItem(COSName.FILTER, COSName.FLATE_DECODE);
    imageDict.setItem(COSName.DECODE_PARMS, decodeParams);
    flateDecode.decode(getIDATInputStream(state), outputStream, imageDict, 0);
    int length = image.getWidth() * image.getHeight();
    byte[] bytes = new byte[length];
    byte[] transparencyTable = state.tRNS.getData();
    byte[] decodedIDAT = outputStream.toByteArray();
    try (ImageInputStream iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(decodedIDAT))) {
        int bitsPerComponent = state.bitsPerComponent;
        int w = 0;
        int neededBits = bitsPerComponent * state.width;
        int bitPadding = neededBits % 8;
        for (int i = 0; i < bytes.length; i++) {
            int idx = (int) iis.readBits(bitsPerComponent);
            if (idx < transparencyTable.length) {
                // Inside the table, use the transparency value
                bytes[i] = transparencyTable[idx];
            } else {
                // Outside the table -> transparent value is 0xFF here.
                bytes[i] = (byte) 0xFF;
            }
            w++;
            if (w == state.width) {
                w = 0;
                iis.readBits(bitPadding);
            }
        }
    }
    return LosslessFactory.prepareImageXObject(doc, bytes, image.getWidth(), image.getHeight(), 8, PDDeviceGray.INSTANCE);
}
Also used : COSDictionary(org.apache.pdfbox.cos.COSDictionary) Filter(org.apache.pdfbox.filter.Filter) ByteArrayInputStream(java.io.ByteArrayInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Example 28 with MemoryCacheImageInputStream

use of javax.imageio.stream.MemoryCacheImageInputStream 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)

Example 29 with MemoryCacheImageInputStream

use of javax.imageio.stream.MemoryCacheImageInputStream in project Lucee by lucee.

the class Image method getMetaData.

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;
    javax.imageio.stream.ImageInputStreamImpl iis = null;
    try {
        if (source instanceof File) {
            iis = new FileImageInputStream((File) source);
        } else if (source == null)
            iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true)));
        else
            iis = new MemoryCacheImageInputStream(is = source.getInputStream());
        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            // pick the first available ImageReader
            ImageReader reader = readers.next();
            IIOMetadata meta = null;
            synchronized (sync) {
                // attach source to the reader
                reader.setInput(iis, true);
                // read metadata of first image
                meta = reader.getImageMetadata(0);
                meta.setFromTree(FORMAT, meta.getAsTree(FORMAT));
                reader.reset();
            }
            // generating dump
            if (parent != null) {
                String[] formatNames = meta.getMetadataFormatNames();
                for (int i = 0; i < formatNames.length; i++) {
                    Node root = meta.getAsTree(formatNames[i]);
                    // print.out(XMLCaster.toString(root));
                    addMetaddata(parent, "metadata", root);
                }
            }
            return meta;
        }
    } catch (Throwable t) {
        ExceptionUtil.rethrowIfNecessary(t);
    } finally {
        ImageUtil.closeEL(iis);
        IOUtil.closeEL(is);
    }
    return null;
}
Also used : FileImageInputStream(javax.imageio.stream.FileImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Node(org.w3c.dom.Node) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) AttributedString(java.text.AttributedString) Point(java.awt.Point) FileImageInputStream(javax.imageio.stream.FileImageInputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageReader(javax.imageio.ImageReader) File(java.io.File)

Example 30 with MemoryCacheImageInputStream

use of javax.imageio.stream.MemoryCacheImageInputStream in project imageio-ext by geosolutions-it.

the class TIFFYCbCrDecompressor method decodeRaw.

public void decodeRaw(byte[] buf, int dstOffset, int bitsPerPixel, int scanlineStride) throws IOException {
    byte[] rows = new byte[3 * srcWidth * chromaSubsampleV];
    int elementsPerPacket = chromaSubsampleH * chromaSubsampleV + 2;
    byte[] packet = new byte[elementsPerPacket];
    if (decompressor != null) {
        int bytesPerRow = 3 * srcWidth;
        byte[] tmpBuf = new byte[bytesPerRow * srcHeight];
        decompressor.decodeRaw(tmpBuf, dstOffset, bitsPerPixel, bytesPerRow);
        ByteArrayInputStream byteStream = new ByteArrayInputStream(tmpBuf);
        stream = new MemoryCacheImageInputStream(byteStream);
    } else {
        stream.seek(offset);
    }
    for (int y = srcMinY; y < srcMinY + srcHeight; y += chromaSubsampleV) {
        // Decode chromaSubsampleV rows
        for (int x = srcMinX; x < srcMinX + srcWidth; x += chromaSubsampleH) {
            try {
                stream.readFully(packet);
            } catch (EOFException e) {
                System.out.println("e = " + e);
                return;
            }
            byte Cb = packet[elementsPerPacket - 2];
            byte Cr = packet[elementsPerPacket - 1];
            int iCb = 0, iCr = 0, iGCb = 0, iGCr = 0;
            if (colorConvert) {
                int Cbp = Cb & 0xff;
                int Crp = Cr & 0xff;
                iCb = iCbTab[Cbp];
                iCr = iCrTab[Crp];
                iGCb = iGCbTab[Cbp];
                iGCr = iGCrTab[Crp];
            }
            int yIndex = 0;
            for (int v = 0; v < chromaSubsampleV; v++) {
                int idx = dstOffset + 3 * (x - srcMinX) + scanlineStride * (y - srcMinY + v);
                // Check if we reached the last scanline
                if (y + v >= srcMinY + srcHeight) {
                    break;
                }
                for (int h = 0; h < chromaSubsampleH; h++) {
                    if (x + h >= srcMinX + srcWidth) {
                        break;
                    }
                    byte Y = packet[yIndex++];
                    if (colorConvert) {
                        int Yp = Y & 0xff;
                        int iY = iYTab[Yp];
                        int iGY = iGYTab[Yp];
                        int iR = iY + iCr;
                        int iG = iGY + iGCb + iGCr;
                        int iB = iY + iCb;
                        byte r = clamp(iR);
                        byte g = clamp(iG);
                        byte b = clamp(iB);
                        buf[idx] = r;
                        buf[idx + 1] = g;
                        buf[idx + 2] = b;
                    } else {
                        buf[idx] = Y;
                        buf[idx + 1] = Cb;
                        buf[idx + 2] = Cr;
                    }
                    idx += 3;
                }
            }
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) EOFException(java.io.EOFException)

Aggregations

MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)54 ImageInputStream (javax.imageio.stream.ImageInputStream)33 ByteArrayInputStream (java.io.ByteArrayInputStream)23 ImageReader (javax.imageio.ImageReader)22 IOException (java.io.IOException)19 InputStream (java.io.InputStream)19 BufferedImage (java.awt.image.BufferedImage)17 FileInputStream (java.io.FileInputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 COSDictionary (org.apache.pdfbox.cos.COSDictionary)8 EOFException (java.io.EOFException)7 ArrayList (java.util.ArrayList)6 COSStream (org.apache.pdfbox.cos.COSStream)6 PDRange (org.apache.pdfbox.pdmodel.common.PDRange)6 Point (java.awt.Point)5 Point2D (java.awt.geom.Point2D)5 ImageReadParam (javax.imageio.ImageReadParam)5 MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)5 Paint (java.awt.Paint)4 Size (org.olat.core.commons.services.image.Size)4