PHP code:
$txt="John has cat and dog."; //plain text
$txt=base64_encode($txt); //base64 encode
$txt=gzdeflate($txt,9); //best compress
$txt=base64_encode($txt); //base64 encode
print_r($txt); //print it
Below code return:
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
I'm trying compress string in Java.
// Encode a String into bytes
String inputString = "John has cat and dog.";
inputString=Base64.encode(inputString);
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
Deflater compresser = new Deflater();
//compresser.setLevel(Deflater.BEST_COMPRESSION);
compresser.setInput(input);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
String outputString = new String(output, 0, compressedDataLength,"UTF-8");
outputString=Base64.encode(outputString);
System.out.println(outputString);
But print wrong string: eD8L
Pz9PP3Q/Pz9NPzRyMz90dys/cnY/TjJKLgUAPygJTA==
must be:
C861zE/KdMqPjPBNjzRyM/B0dyuNcnbKTjJKLgUA
How fix it? Thanks.
Use Deflater
like this :
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compresser);
deflaterOutputStream.write(input);
deflaterOutputStream.close();
byte[] output = stream.toByteArray();
To decompress what is compressed:
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
Inflater decompresser = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream2, decompresser);
inflaterOutputStream.write(output);
inflaterOutputStream.close();
byte[] output2 = stream2.toByteArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With