// From http://code.calum.org/ /* * Heavily based around this code: * http://www.java-tips.org/java-se-tips/java.util.zip/how-to-compress-a-byte-array.html * */ public static byte[] compressByteArray(byte[] input){ int startBytes = input.length; // System.out.println("compressByteArray: input size is " + startBytes); // Create the compressor with highest level of compression Deflater compressor = new Deflater(); compressor.setLevel(Deflater.BEST_COMPRESSION); // Give the compressor the data to compress compressor.setInput(input); compressor.finish(); // Create an expandable byte array to hold the compressed data. // You cannot use an array that's the same size as the orginal because // there is no guarantee that the compressed data will be smaller than // the uncompressed data. ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length); // Compress the data byte[] buf = new byte[1024]; while (!compressor.finished()) { int count = compressor.deflate(buf); bos.write(buf, 0, count); } try { bos.close(); } catch (IOException e) { } // Get the compressed data byte[] compressedData = bos.toByteArray(); int endBytes = compressedData.length; // System.out.println("compressByteArray: output is " + endBytes + " bytes"); // System.out.println("Ratio: " + (( 100D / startBytes ) * endBytes) + "%"); return compressedData; }