Search in sources :

Example 1 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project jdk8u_jdk by JetBrains.

the class BooleanAttributes method test.

public static void test(String mimeType, boolean useStreamMeta, String metaXml, String... boolXpaths) throws Exception {
    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType(mimeType).next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    ImageWriteParam param = null;
    IIOMetadata streamMeta = iw.getDefaultStreamMetadata(param);
    IIOMetadata imageMeta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), param);
    IIOMetadata meta = useStreamMeta ? streamMeta : imageMeta;
    Source src = new StreamSource(new StringReader(metaXml));
    DOMResult dst = new DOMResult();
    transform(src, dst);
    Document doc = (Document) dst.getNode();
    Element node = doc.getDocumentElement();
    String metaFormat = node.getNodeName();
    // Verify that the default metadata gets formatted correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, false);
    meta.mergeTree(metaFormat, node);
    // Verify that the merged metadata gets formatte correctly.
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
    iw.write(streamMeta, new IIOImage(img, null, imageMeta), param);
    iw.dispose();
    ios.close();
    ImageReader ir = ImageIO.getImageReader(iw);
    byte[] bytes = os.toByteArray();
    if (bytes.length == 0)
        throw new AssertionError("Zero length image file");
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    if (useStreamMeta)
        meta = ir.getStreamMetadata();
    else
        meta = ir.getImageMetadata(0);
    // Verify again after writing and re-reading the image
    verify(meta.getAsTree(metaFormat), boolXpaths, true);
}
Also used : DOMResult(javax.xml.transform.dom.DOMResult) StreamSource(javax.xml.transform.stream.StreamSource) Element(org.w3c.dom.Element) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) ImageWriter(javax.imageio.ImageWriter) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageWriteParam(javax.imageio.ImageWriteParam) Document(org.w3c.dom.Document) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) IIOImage(javax.imageio.IIOImage) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) ByteArrayInputStream(java.io.ByteArrayInputStream) StringReader(java.io.StringReader) ImageReader(javax.imageio.ImageReader) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 2 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project jdk8u_jdk by JetBrains.

the class ItxtUtf8Test method runTest.

public static void runTest(boolean dump, boolean truncate) throws Exception {
    String format = "javax_imageio_png_1.0";
    BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageOutputStream ios = new MemoryCacheImageOutputStream(os);
    iw.setOutput(ios);
    IIOMetadata meta = iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, itxt, entry;
    root = doc.getDocumentElement();
    root.appendChild(itxt = doc.createElement("iTXt"));
    itxt.appendChild(entry = doc.createElement("iTXtEntry"));
    entry.setAttribute("keyword", "verbatim");
    entry.setAttribute("compressionFlag", "false");
    entry.setAttribute("compressionMethod", "0");
    entry.setAttribute("languageTag", "x-circled");
    entry.setAttribute("translatedKeyword", VERBATIM);
    entry.setAttribute("text", TEXT);
    itxt.appendChild(entry = doc.createElement("iTXtEntry"));
    entry.setAttribute("keyword", "compressed");
    entry.setAttribute("compressionFlag", "true");
    entry.setAttribute("compressionMethod", "0");
    entry.setAttribute("languageTag", "x-circled");
    entry.setAttribute("translatedKeyword", COMPRESSED);
    entry.setAttribute("text", TEXT);
    meta.mergeTree(format, root);
    iw.write(new IIOImage(img, null, meta));
    iw.dispose();
    byte[] bytes = os.toByteArray();
    if (dump)
        System.out.write(bytes);
    if (findBytes(VBYTES, bytes) < 0)
        throw new AssertionError("verbatim block not found");
    if (findBytes(CBYTES, bytes) < 0)
        throw new AssertionError("compressed block not found");
    int length = bytes.length;
    if (truncate)
        length = findBytes(VBYTES, bytes) + 32;
    ImageReader ir = ImageIO.getImageReader(iw);
    ByteArrayInputStream is = new ByteArrayInputStream(bytes, 0, length);
    ImageInputStream iis = new MemoryCacheImageInputStream(is);
    ir.setInput(iis);
    meta = ir.getImageMetadata(0);
    Node node = meta.getAsTree(format);
    for (node = node.getFirstChild(); !"iTXt".equals(node.getNodeName()); node = node.getNextSibling()) ;
    boolean verbatimSeen = false, compressedSeen = false;
    for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) {
        entry = (Element) node;
        String keyword = entry.getAttribute("keyword");
        String translatedKeyword = entry.getAttribute("translatedKeyword");
        String text = entry.getAttribute("text");
        if ("verbatim".equals(keyword)) {
            if (verbatimSeen)
                throw new AssertionError("Duplicate");
            verbatimSeen = true;
            if (!VERBATIM.equals(translatedKeyword))
                throw new AssertionError("Wrong translated keyword");
            if (!TEXT.equals(text))
                throw new AssertionError("Wrong text");
        } else if ("compressed".equals(keyword)) {
            if (compressedSeen)
                throw new AssertionError("Duplicate");
            compressedSeen = true;
            if (!COMPRESSED.equals(translatedKeyword))
                throw new AssertionError("Wrong translated keyword");
            if (!TEXT.equals(text))
                throw new AssertionError("Wrong text");
        } else {
            throw new AssertionError("Unexpected keyword");
        }
    }
    if (!(verbatimSeen && compressedSeen))
        throw new AssertionError("Missing chunk");
}
Also used : Element(org.w3c.dom.Element) ImageInputStream(javax.imageio.stream.ImageInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) Node(org.w3c.dom.Node) ImageWriter(javax.imageio.ImageWriter) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) DOMImplementation(org.w3c.dom.DOMImplementation) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) IIOImage(javax.imageio.IIOImage) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) IIOMetadata(javax.imageio.metadata.IIOMetadata) ByteArrayInputStream(java.io.ByteArrayInputStream) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) ImageReader(javax.imageio.ImageReader) ImageOutputStream(javax.imageio.stream.ImageOutputStream) MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 3 with MemoryCacheImageOutputStream

use of javax.imageio.stream.MemoryCacheImageOutputStream in project zm-mailbox by Zimbra.

the class NativeFormatter method getResizedImageData.

/**
     * If the image stored in the {@code MimePart} exceeds the given width,
     * shrinks the image and returns the shrunk data.  If the
     * image width is smaller than {@code maxWidth} or resizing is not supported,
     * returns {@code null}.
     */
private static byte[] getResizedImageData(MimePart mp, Integer maxWidth, Integer maxHeight) throws IOException, MessagingException {
    ImageReader reader = null;
    ImageWriter writer = null;
    InputStream in = null;
    if (maxWidth == null)
        maxWidth = LC.max_image_size_to_resize.intValue();
    if (maxHeight == null)
        maxHeight = LC.max_image_size_to_resize.intValue();
    try {
        // Get ImageReader for stream content.
        reader = ImageUtil.getImageReader(Mime.getContentType(mp), mp.getFileName());
        if (reader == null) {
            log.debug("No ImageReader available.");
            return null;
        }
        // Read message content.
        in = mp.getInputStream();
        reader.setInput(new MemoryCacheImageInputStream(in));
        BufferedImage img = reader.read(0);
        int width = img.getWidth(), height = img.getHeight();
        if (width <= maxWidth && height <= maxHeight) {
            log.debug("Image %dx%d is less than max %dx%d.  Not resizing.", width, height, maxWidth, maxHeight);
            return null;
        }
        // Resize.
        writer = ImageIO.getImageWriter(reader);
        if (writer == null) {
            log.debug("No ImageWriter available.");
            return null;
        }
        double ratio = Math.min((double) maxWidth / width, (double) maxHeight / height);
        width *= ratio;
        height *= ratio;
        BufferedImage small = ImageUtil.resize(img, width, height);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer.setOutput(new MemoryCacheImageOutputStream(out));
        writer.write(small);
        return out.toByteArray();
    } finally {
        ByteUtil.closeStream(in);
        if (reader != null) {
            reader.dispose();
        }
        if (writer != null) {
            writer.dispose();
        }
    }
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) PushbackInputStream(java.io.PushbackInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) InputStream(java.io.InputStream) ImageWriter(javax.imageio.ImageWriter) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage)

Example 4 with MemoryCacheImageOutputStream

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

the class LZWFilter method encode.

/**
 * {@inheritDoc}
 */
@Override
protected void encode(InputStream rawData, OutputStream encoded, COSDictionary parameters) throws IOException {
    List<byte[]> codeTable = createCodeTable();
    int chunk = 9;
    byte[] inputPattern = null;
    try (MemoryCacheImageOutputStream out = new MemoryCacheImageOutputStream(encoded)) {
        out.writeBits(CLEAR_TABLE, chunk);
        int foundCode = -1;
        int r;
        while ((r = rawData.read()) != -1) {
            byte by = (byte) r;
            if (inputPattern == null) {
                inputPattern = new byte[] { by };
                foundCode = by & 0xff;
            } else {
                inputPattern = Arrays.copyOf(inputPattern, inputPattern.length + 1);
                inputPattern[inputPattern.length - 1] = by;
                int newFoundCode = findPatternCode(codeTable, inputPattern);
                if (newFoundCode == -1) {
                    // use previous
                    chunk = calculateChunk(codeTable.size() - 1, 1);
                    out.writeBits(foundCode, chunk);
                    // create new table entry
                    codeTable.add(inputPattern);
                    if (codeTable.size() == 4096) {
                        // code table is full
                        out.writeBits(CLEAR_TABLE, chunk);
                        codeTable = createCodeTable();
                    }
                    inputPattern = new byte[] { by };
                    foundCode = by & 0xff;
                } else {
                    foundCode = newFoundCode;
                }
            }
        }
        if (foundCode != -1) {
            chunk = calculateChunk(codeTable.size() - 1, 1);
            out.writeBits(foundCode, chunk);
        }
        // PPDFBOX-1977: the decoder wouldn't know that the encoder would output
        // an EOD as code, so he would have increased his own code table and
        // possibly adjusted the chunk. Therefore, the encoder must behave as
        // if the code table had just grown and thus it must be checked it is
        // needed to adjust the chunk, based on an increased table size parameter
        chunk = calculateChunk(codeTable.size(), 1);
        out.writeBits(EOD, chunk);
        // pad with 0
        out.writeBits(0, 7);
        // must do or file will be empty :-(
        out.flush();
    }
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream)

Example 5 with MemoryCacheImageOutputStream

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

the class LosslessFactory method createAlphaFromARGBImage.

/**
 * Creates a grayscale Flate encoded PDImageXObject from the alpha channel
 * of an image.
 *
 * @param document the document where the image will be created.
 * @param image an ARGB image.
 *
 * @return the alpha channel of an image as a grayscale image.
 *
 * @throws IOException if something goes wrong
 */
private static PDImageXObject createAlphaFromARGBImage(PDDocument document, BufferedImage image) throws IOException {
    // save it directly
    if (!image.getColorModel().hasAlpha()) {
        return null;
    }
    // extract the alpha information
    WritableRaster alphaRaster = image.getAlphaRaster();
    if (alphaRaster == null) {
        // happens sometimes (PDFBOX-2654) despite colormodel claiming to have alpha
        return createAlphaFromARGBImage2(document, image);
    }
    int[] pixels = alphaRaster.getPixels(0, 0, alphaRaster.getWidth(), alphaRaster.getHeight(), (int[]) null);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int bpc;
    if (image.getTransparency() == Transparency.BITMASK) {
        bpc = 1;
        try (MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream(bos)) {
            int width = alphaRaster.getWidth();
            int p = 0;
            for (int pixel : pixels) {
                mcios.writeBit(pixel);
                ++p;
                if (p % width == 0) {
                    while (mcios.getBitOffset() != 0) {
                        mcios.writeBit(0);
                    }
                }
            }
            mcios.flush();
        }
    } else {
        bpc = 8;
        for (int pixel : pixels) {
            bos.write(pixel);
        }
    }
    PDImageXObject pdImage = prepareImageXObject(document, bos.toByteArray(), image.getWidth(), image.getHeight(), bpc, PDDeviceGray.INSTANCE);
    return pdImage;
}
Also used : MemoryCacheImageOutputStream(javax.imageio.stream.MemoryCacheImageOutputStream) WritableRaster(java.awt.image.WritableRaster) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

MemoryCacheImageOutputStream (javax.imageio.stream.MemoryCacheImageOutputStream)29 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 ImageOutputStream (javax.imageio.stream.ImageOutputStream)16 BufferedImage (java.awt.image.BufferedImage)14 IIOImage (javax.imageio.IIOImage)13 ImageWriter (javax.imageio.ImageWriter)12 ImageWriteParam (javax.imageio.ImageWriteParam)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 IOException (java.io.IOException)7 ImageReader (javax.imageio.ImageReader)5 IIOMetadata (javax.imageio.metadata.IIOMetadata)4 WritableRaster (java.awt.image.WritableRaster)3 OutputStream (java.io.OutputStream)3 ImageTypeSpecifier (javax.imageio.ImageTypeSpecifier)3 ImageInputStream (javax.imageio.stream.ImageInputStream)3 MemoryCacheImageInputStream (javax.imageio.stream.MemoryCacheImageInputStream)3 Graphics2D (java.awt.Graphics2D)2 AffineTransform (java.awt.geom.AffineTransform)2 InputStream (java.io.InputStream)2 JPEGImageWriteParam (javax.imageio.plugins.jpeg.JPEGImageWriteParam)2