Example usage for java.util.zip Deflater Deflater

List of usage examples for java.util.zip Deflater Deflater

Introduction

In this page you can find the example usage for java.util.zip Deflater Deflater.

Prototype

public Deflater() 

Source Link

Document

Creates a new compressor with the default compression level.

Usage

From source file:org.getspout.spoutapi.packet.PacketCustomBlockChunkOverride.java

@Override
public void compress() {
    if (!compressed) {
        if (data != null && hasData) {
            Deflater deflater = new Deflater();
            deflater.setInput(data);/* w ww  . ja  v  a  2s  .  com*/
            deflater.setLevel(Deflater.BEST_COMPRESSION);
            deflater.finish();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int bytesCompressed = deflater.deflate(buffer);
                bos.write(buffer, 0, bytesCompressed);
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = bos.toByteArray();
        }
        compressed = true;
    }
}

From source file:com.itude.mobile.android.util.DataUtil.java

/**
 * Compress byte array /*from ww  w .  ja va 2  s.c om*/
 * 
 * @param uncompressed byte array
 * @return compressed byte array
 */
public byte[] compress(byte[] uncompressed) {
    byte[] result = null;

    Deflater deflater = new Deflater();
    deflater.setInput(uncompressed);
    deflater.finish();

    // Create an expandable byte array to hold the compressed data. 
    // You cannot use an array that's the same size as the original because 
    // there is no guarantee that the compressed data will be smaller than 
    // the uncompressed data. 

    ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressed.length);

    // Compress the data 
    byte[] buf = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buf);
        bos.write(buf, 0, count);
    }
    deflater.end();

    try {
        bos.close();
    } catch (IOException e) {
        MBLog.w(TAG, "Unable to close stream");
    }

    // Get the compressed data 

    result = bos.toByteArray();

    return result;
}

From source file:org.hyperic.hq.livedata.agent.commands.LiveData_result.java

private String compress(String s) throws IOException {
    Deflater compressor = new Deflater();
    compressor.setInput(s.getBytes("UTF-8"));
    compressor.finish();/*from   www. j  av a2 s.com*/

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }

    bos.close();

    byte[] compressedData = bos.toByteArray();
    return Base64.encode(compressedData);
}

From source file:org.getspout.spoutapi.packet.PacketAddonData.java

@Override
public void compress() {
    if (!compressed) {
        if (data != null) {
            Deflater deflater = new Deflater();
            deflater.setInput(data);//  w  ww.java 2  s .  c  o  m
            deflater.setLevel(Deflater.BEST_COMPRESSION);
            deflater.finish();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int bytesCompressed = deflater.deflate(buffer);
                bos.write(buffer, 0, bytesCompressed);
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = bos.toByteArray();
        }
        compressed = true;
    }
}

From source file:juicebox.tools.utils.original.Preprocessor.java

public Preprocessor(File outputFile, String genomeId, List<Chromosome> chromosomes) {
    this.genomeId = genomeId;
    this.outputFile = outputFile;
    this.matrixPositions = new LinkedHashMap<String, IndexEntry>();

    this.chromosomes = chromosomes;
    chromosomeIndexes = new Hashtable<String, Integer>();
    for (int i = 0; i < chromosomes.size(); i++) {
        chromosomeIndexes.put(chromosomes.get(i).getName(), i);
    }//from w  w w.j a v a  2s.  c  o  m

    compressor = new Deflater();
    compressor.setLevel(Deflater.DEFAULT_COMPRESSION);

    this.tmpDir = null;

}

From source file:org.getspout.spout.packet.PacketAddonData.java

public void compress() {
    if (!compressed) {
        if (data != null) {
            Deflater deflater = new Deflater();
            deflater.setInput(data);/*from   w ww. ja  v a 2s . c o m*/
            deflater.setLevel(Deflater.BEST_COMPRESSION);
            deflater.finish();
            ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);
            byte[] buffer = new byte[1024];
            while (!deflater.finished()) {
                int bytesCompressed = deflater.deflate(buffer);
                bos.write(buffer, 0, bytesCompressed);
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            data = bos.toByteArray();
        }
        compressed = true;
    }
}

From source file:org.apache.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void setup(PDFDocument doc) {
    super.setup(doc);
    ColorModel cm = ((ImageRawPNG) this.image).getColorModel();
    if (cm instanceof IndexColorModel) {
        numberOfInterleavedComponents = 1;
    } else {/* w  w w . ja  va  2s  . co m*/
        // this can be 1 (gray), 2 (gray + alpha), 3 (rgb) or 4 (rgb + alpha)
        // numberOfInterleavedComponents = (cm.hasAlpha() ? 1 : 0) + cm.getNumColorComponents();
        numberOfInterleavedComponents = cm.getNumComponents();
    }

    // set up image compression for non-alpha channel
    FlateFilter flate;
    try {
        flate = new FlateFilter();
        flate.setApplied(true);
        flate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
        if (numberOfInterleavedComponents < 3) {
            // means palette (1) or gray (1) or gray + alpha (2)
            flate.setColors(1);
        } else {
            // means rgb (3) or rgb + alpha (4)
            flate.setColors(3);
        }
        flate.setColumns(image.getSize().getWidthPx());
        flate.setBitsPerComponent(this.getBitsPerComponent());
    } catch (PDFFilterException e) {
        throw new RuntimeException("FlateFilter configuration error", e);
    }
    this.pdfFilter = flate;
    this.disallowMultipleFilters();

    // Handle transparency channel if applicable; note that for palette images the transparency is
    // not TRANSLUCENT
    if (cm.hasAlpha() && cm.getTransparency() == ColorModel.TRANSLUCENT) {
        doc.getProfile().verifyTransparencyAllowed(image.getInfo().getOriginalURI());
        // TODO: Implement code to combine image with background color if transparency is not allowed
        // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha channel
        // and then deflate it back again
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream(baos, new Deflater());
        InputStream in = ((ImageRawStream) image).createInputStream();
        try {
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            // offset is the byte offset of the alpha component
            int offset = numberOfInterleavedComponents - 1; // 1 for GA, 3 for RGBA
            int numColumns = image.getSize().getWidthPx();
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // read line by line; the first byte holds the filter
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, 1);
                    offset += numberOfInterleavedComponents;
                }
                offset = numberOfInterleavedComponents - 1;
            }
            dos.close();
        } catch (IOException e) {
            throw new RuntimeException("Error processing transparency channel:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
        // set up alpha channel compression
        FlateFilter transFlate;
        try {
            transFlate = new FlateFilter();
            transFlate.setApplied(true);
            transFlate.setPredictor(FlateFilter.PREDICTION_PNG_OPT);
            transFlate.setColors(1);
            transFlate.setColumns(image.getSize().getWidthPx());
            transFlate.setBitsPerComponent(this.getBitsPerComponent());
        } catch (PDFFilterException e) {
            throw new RuntimeException("FlateFilter configuration error", e);
        }
        BitmapImage alphaMask = new BitmapImage("Mask:" + this.getKey(), image.getSize().getWidthPx(),
                image.getSize().getHeightPx(), baos.toByteArray(), null);
        alphaMask.setPDFFilter(transFlate);
        alphaMask.disallowMultipleFilters();
        alphaMask.setColorSpace(new PDFDeviceColorSpace(PDFDeviceColorSpace.DEVICE_GRAY));
        softMask = doc.addImage(null, alphaMask).makeReference();
    }
}

From source file:com.asual.lesscss.ResourcePackage.java

private static byte[] deflate(byte[] input) throws IOException {
    Deflater deflater = new Deflater();
    deflater.setLevel(Deflater.BEST_COMPRESSION);
    deflater.setInput(input);//from   w ww  . j ava 2 s.c o m
    deflater.finish();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
    byte[] buf = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buf);
        baos.write(buf, 0, count);
    }
    baos.close();
    return baos.toByteArray();
}

From source file:Comman.Tool.java

public byte[] Image_compress(final byte[] data) {
    if (data == null || data.length == 0) {
        return new byte[0];
    }//from ww w . j ava 2  s.c  o  m

    try (final ByteArrayOutputStream out = new ByteArrayOutputStream(data.length)) {
        final Deflater deflater = new Deflater();
        deflater.setInput(data);

        deflater.finish();
        final byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            out.write(buffer, 0, deflater.deflate(buffer));
        }

        return out.toByteArray();
    } catch (final IOException e) {
        System.err.println("Compression failed! Returning the original data...");
        return data;
    }
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public int sendCompressedFrame(List<Map<String, byte[]>> keyValuesList) throws IOException {
    output.writeByte(PROTOCOL_VERSION);/*from   w w w  .  j  av a 2 s. co m*/
    output.writeByte(FRAME_COMPRESSED);

    ByteArrayOutputStream uncompressedBytes = new ByteArrayOutputStream();
    DataOutputStream uncompressedOutput = new DataOutputStream(uncompressedBytes);
    for (Map<String, byte[]> keyValues : keyValuesList) {
        logger.trace("Adding data frame");
        sendDataFrame(uncompressedOutput, keyValues);
    }
    uncompressedOutput.close();
    Deflater compressor = new Deflater();
    byte[] uncompressedData = uncompressedBytes.toByteArray();
    if (logger.isDebugEnabled()) {
        logger.debug("Deflating data : " + uncompressedData.length + " bytes");
    }
    if (logger.isTraceEnabled()) {
        HexDump.dump(uncompressedData, 0, System.out, 0);
    }
    compressor.setInput(uncompressedData);
    compressor.finish();

    ByteArrayOutputStream compressedBytes = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buffer);
        compressedBytes.write(buffer, 0, count);
    }
    compressedBytes.close();
    byte[] compressedData = compressedBytes.toByteArray();
    if (logger.isDebugEnabled()) {
        logger.debug("Deflated data : " + compressor.getTotalOut() + " bytes");
    }
    if (logger.isTraceEnabled()) {
        HexDump.dump(compressedData, 0, System.out, 0);
    }

    output.writeInt(compressor.getTotalOut());
    output.write(compressedData);
    output.flush();

    if (logger.isDebugEnabled()) {
        logger.debug("Sending compressed frame : " + keyValuesList.size() + " frames");
    }
    return 6 + compressor.getTotalOut();
}