Package org.apache.commons.io.output

Examples of org.apache.commons.io.output.ByteArrayOutputStream


        if (!skipAfter(in, PACKET_HEADER_END)) {
            throw new IOException("Invalid XMP packet header!");
        }
        //TODO think about not buffering this but for example, parse in another thread
        //ex. using PipedInput/OutputStream
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        //TODO Do with TeeInputStream when Commons IO 1.4 is available
        if (!skipAfter(in, PACKET_TRAILER, baout)) {
            throw new IOException("XMP packet not properly terminated!");
        }

        Metadata metadata = XMPParser.parseXMP(
                new StreamSource(new ByteArrayInputStream(baout.toByteArray())));
        return metadata;
    }
View Full Code Here


     * and icc profile if any.
     *
     * @return true if loaded false for any error
     */
    protected boolean loadOriginalData() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayOutputStream iccStream = null;
        int index = 0;
        boolean cont = true;

        try {
            byte[] readBuf = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(readBuf)) != -1) {
                baos.write(readBuf, 0, bytesRead);
            }
        } catch (java.io.IOException ex) {
            log.error("Error while loading image (Jpeg): " + ex.getMessage(), ex);
            return false;
        } finally {
            IOUtils.closeQuietly(inputStream);
            inputStream = null;
        }

        this.raw = baos.toByteArray();
        this.bitsPerPixel = 8;
        this.isTransparent = false;

        //Check for SOI (Start of image) marker (FFD8)
        if (this.raw.length > (index + 2)
                && uByte(this.raw[index]) == 255 /*0xFF*/
                && uByte(this.raw[index + 1]) == 216 /*0xD8*/) {
            index += 2;

            while (index < this.raw.length && cont) {
                //check to be sure this is the begining of a header
                if (this.raw.length > (index + 2)
                        && uByte(this.raw[index]) == 255 /*0xFF*/) {

                    //192 or 194 are the header bytes that contain
                    // the jpeg width height and color depth.
                    if (uByte(this.raw[index + 1]) == 192 /*0xC0*/
                            || uByte(this.raw[index + 1]) == 194 /*0xC2*/) {

                        this.height = calcBytes(this.raw[index + 5],
                                                  this.raw[index + 6]);
                        this.width = calcBytes(this.raw[index + 7],
                                                 this.raw[index + 8]);

                        if (this.raw[index + 9] == 1) {
                            this.colorSpace = ColorSpace.getInstance(
                              ColorSpace.CS_GRAY);
                        } else if (this.raw[index + 9] == 3) {
                            this.colorSpace = ColorSpace.getInstance(
                              ColorSpace.CS_LINEAR_RGB);
                        } else if (this.raw[index + 9] == 4) {
                            // howto create CMYK color space
                            /*
                            this.colorSpace = ColorSpace.getInstance(
                              ColorSpace.CS_CIEXYZ);
                            */
                            this.colorSpace = CMYKColorSpace.getInstance();
                        } else {
                            log.error("Unknown ColorSpace for image: "
                                                   + "");
                            return false;
                        }

                        if (foundICCProfile) {
                            cont = false;
                            break;
                        }
                        index += calcBytes(this.raw[index + 2],
                                           this.raw[index + 3]) + 2;

                    } else if (uByte(this.raw[index + 1]) == 226 /*0xE2*/
                                   && this.raw.length > (index + 60)) {
                        // Check if ICC profile
                        byte[] iccString = new byte[11];
                        System.arraycopy(this.raw, index + 4,
                                         iccString, 0, 11);

                        if ("ICC_PROFILE".equals(new String(iccString))) {
                            int chunkSize = calcBytes(
                                              this.raw[index + 2],
                                              this.raw[index + 3]) + 2;

                            if (iccStream == null) {
                                iccStream = new ByteArrayOutputStream();
                            }
                            iccStream.write(this.raw,
                                            index + 18, chunkSize - 18);

                        }

                        index += calcBytes(this.raw[index + 2],
                                           this.raw[index + 3]) + 2;
                    // Check for Adobe APPE Marker
                    } else if ((uByte(this.raw[index]) == 0xff
                                && uByte(this.raw[index + 1]) == 0xee
                                && uByte(this.raw[index + 2]) == 0
                                && uByte(this.raw[index + 3]) == 14
                                && "Adobe".equals(new String(this.raw, index + 4, 5)))) {
                        // The reason for reading the APPE marker is that Adobe Photoshop
                        // generates CMYK JPEGs with inverted values. The correct thing
                        // to do would be to interpret the values in the marker, but for now
                        // only assume that if APPE marker is present and colorspace is CMYK,
                        // the image is inverted.
                        hasAPPEMarker = true;

                        index += calcBytes(this.raw[index + 2],
                                           this.raw[index + 3]) + 2;
                    } else {
                        index += calcBytes(this.raw[index + 2],
                                           this.raw[index + 3]) + 2;
                    }

                } else {
                    cont = false;
                }
            }
        } else {
            log.error("Error while loading "
                         + "JpegImage - Invalid JPEG Header.");
            return false;
        }
        if (iccStream != null && iccStream.size() > 0) {
            int padding = (8 - (iccStream.size() % 8)) % 8;
            if (padding != 0) {
                try {
                    iccStream.write(new byte[padding]);
                } catch (Exception ex) {
                    log.error("Error while aligning ICC stream: " + ex.getMessage(), ex);
                    return false;
                }
            }
            try {
                iccProfile = ICC_Profile.getInstance(iccStream.toByteArray());
            } catch (IllegalArgumentException iae) {
                log.warn("An ICC profile is present but it is invalid ("
                        + iae.getMessage() + "). The color profile will be ignored. ("
                        + this.getOriginalURI() + ")");
            }
View Full Code Here

        } else {
            //TODO Revisit after the image library redesign!!!
            //Convert the decoded bitmaps to a BufferedImage
            BufferedImage bufImage = createBufferedImageFromBitmaps(fopImage);
            ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/png");
            ByteArrayOutputStream baout = new ByteArrayOutputStream();
            writer.writeImage(bufImage, baout);
            rawData = baout.toByteArray();
        }
        if (rawData == null) {
            log.warn(FONode.decorateWithContextInfo("Image could not be embedded: "
                    + fopImage.getOriginalURI(), abstractGraphic));
            return;
View Full Code Here

    public void drawBufferedImage(BufferedImage bi, int resolution, int x, int y, int w, int h) {
        int afpx = mpts2units(x);
        int afpy = mpts2units(y);
        int afpw = mpts2units(w);
        int afph = mpts2units(h);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        try {
            //Serialize image
            writeImage(bi, baout);
            byte[] buf = baout.toByteArray();

            //Generate image
            ImageObject io = _afpDataStream.getImageObject(afpx, afpy, afpw, afph);
            io.setImageParameters(
                resolution, resolution,
View Full Code Here

        imageRGB = prepareImage(imageRGB);

        ImageEncodingHelper imageEncodingHelperBGR = new ImageEncodingHelper(imageBGR);
        ImageEncodingHelper imageEncodingHelperRGB = new ImageEncodingHelper(imageRGB);

        ByteArrayOutputStream baosBGR = new ByteArrayOutputStream();
        imageEncodingHelperBGR.encode(baosBGR);

        ByteArrayOutputStream baosRGB = new ByteArrayOutputStream();
        imageEncodingHelperRGB.encode(baosRGB);

        assertTrue(Arrays.equals(baosBGR.toByteArray(), baosRGB.toByteArray()));
    }
View Full Code Here

        if (outputDir != null) {
            File tgtFile = new File(outputDir, name + ".pdf");
            out = new FileOutputStream(tgtFile);
            out = new BufferedOutputStream(out);
        } else {
            out = new ByteArrayOutputStream();
        }
        try {
            Source src = new DOMSource(intermediate);
            parseAndRender(src, out, MimeConstants.MIME_PDF);
        } finally {
View Full Code Here

     * @return the generated PDF data
     * @throws Exception if the conversion fails
     */
    protected byte[] convertFO(File foFile, FOUserAgent ua, boolean dumpPdfFile)
            throws Exception {
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, ua, baout);
        Transformer transformer = tFactory.newTransformer();
        Source src = new StreamSource(foFile);
        SAXResult res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);
        final byte[] result = baout.toByteArray();
        if (dumpPdfFile) {
            final File outFile = new File(foFile.getParentFile(), foFile.getName() + ".pdf");
            FileUtils.writeByteArrayToFile(outFile, result);
        }
        return result;
View Full Code Here

                throws FOPException, TransformerException, IOException {

        FOUserAgent foUserAgent = getFOUserAgent();

        //Setup output
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //Setup FOP
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        //Make sure the XSL transformation's result is piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        //Start the transformation and rendering process
        transformer.transform(src, res);

        //Return the result
        sendPDF(out.toByteArray(), response);
    }
View Full Code Here

        }

        ColorSpace colorSpace = null;
        boolean appeFound = false;
        int sofType = 0;
        ByteArrayOutputStream iccStream = null;

        Source src = session.needSource(info.getOriginalURI());
        ImageInputStream in = ImageUtil.needImageInputStream(src);
        JPEGFile jpeg = new JPEGFile(in);
        in.mark();
        try {
            outer:
            while (true) {
                int reclen;
                int segID = jpeg.readMarkerSegment();
                if (log.isTraceEnabled()) {
                    log.trace("Seg Marker: " + Integer.toHexString(segID));
                }
                switch (segID) {
                case EOI:
                    log.trace("EOI found. Stopping.");
                    break outer;
                case SOS:
                    log.trace("SOS found. Stopping early."); //TODO Not sure if this is safe
                    break outer;
                case SOI:
                case NULL:
                    break;
                case SOF0: //baseline
                case SOF1: //extended sequential DCT
                case SOF2: //progressive (since PDF 1.3)
                case SOFA: //progressive (since PDF 1.3)
                    sofType = segID;
                    if (log.isTraceEnabled()) {
                        log.trace("SOF: " + Integer.toHexString(sofType));
                    }
                    in.mark();
                    try {
                        reclen = jpeg.readSegmentLength();
                        in.skipBytes(1); //data precision
                        in.skipBytes(2); //height
                        in.skipBytes(2); //width
                        int numComponents = in.readUnsignedByte();
                        if (numComponents == 1) {
                            colorSpace = ColorSpace.getInstance(
                              ColorSpace.CS_GRAY);
                        } else if (numComponents == 3) {
                            colorSpace = ColorSpace.getInstance(
                              ColorSpace.CS_LINEAR_RGB);
                        } else if (numComponents == 4) {
                            colorSpace = ColorSpaces.getDeviceCMYKColorSpace();
                        } else {
                            throw new ImageException("Unsupported ColorSpace for image "
                                        + info
                                        + ". The number of components supported are 1, 3 and 4.");
                        }
                    } finally {
                        in.reset();
                    }
                    in.skipBytes(reclen);
                    break;
                case APP2: //ICC (see ICC1V42.pdf)
                    in.mark();
                    try {
                        reclen = jpeg.readSegmentLength();
                        // Check for ICC profile
                        byte[] iccString = new byte[11];
                        in.readFully(iccString);
                        in.skipBytes(1); //string terminator (null byte)

                        if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) {
                            in.skipBytes(2); //chunk sequence number and total number of chunks
                            int payloadSize = reclen - 2 - 12 - 2;
                            if (ignoreColorProfile(hints)) {
                                log.debug("Ignoring ICC profile data in JPEG");
                                in.skipBytes(payloadSize);
                            } else {
                                byte[] buf = new byte[payloadSize];
                                in.readFully(buf);
                                if (iccStream == null) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("JPEG has an ICC profile");
                                        DataInputStream din = new DataInputStream(new ByteArrayInputStream(buf));
                                        log.debug("Declared ICC profile size: " + din.readInt());
                                    }
                                    //ICC profiles can be split into several chunks
                                    //so collect in a byte array output stream
                                    iccStream = new ByteArrayOutputStream();
                                }
                                iccStream.write(buf);
                            }
                        }
                    } finally {
                        in.reset();
                    }
View Full Code Here

        while (iter.hasNext()) {
            Integer cid = (Integer)iter.next();
            cidSubset.set(cid.intValue());
        }
        PDFStream cidSet = makeStream(null, true);
        ByteArrayOutputStream baout = new ByteArrayOutputStream(cidSubset.length() / 8 + 1);
        int value = 0;
        for (int i = 0, c = cidSubset.length(); i < c; i++) {
            int shift = i % 8;
            boolean b = cidSubset.get(i);
            if (b) {
                value |= 1 << 7 - shift;
            }
            if (shift == 7) {
                baout.write(value);
                value = 0;
            }
        }
        baout.write(value);
        try {
            cidSet.setData(baout.toByteArray());
            descriptor.setCIDSet(cidSet);
        } catch (IOException ioe) {
            log.error(
                    "Failed to write CIDSet [" + cidFont + "] "
                    + cidFont.getFontName(), ioe);
View Full Code Here

TOP

Related Classes of org.apache.commons.io.output.ByteArrayOutputStream

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.