Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(de)compress base64 string

Tags:

java

php

base64

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.

like image 386
Jarosław Maciejewski Avatar asked Jan 14 '23 16:01

Jarosław Maciejewski


1 Answers

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();
like image 151
Akdeniz Avatar answered Jan 22 '23 06:01

Akdeniz