jobukkit
jobukkit

Reputation: 2670

How to compress a string using GZip or similar in Dart?

I want to compress a string in Dart (in the browser). I tried this:

import 'package:archive/archive.dart';

[...]

List<int> stringBytes = UTF8.encode(myString);
List<int> gzipBytes = new GZipEncoder().encode(stringBytes);
String compressedString = UTF8.decode(gzipBytes, allowMalformed: true);

Obviously UTF8.decode is not intended for this and it doesn't work (file is unreadable).

What is the right way to compress a string in Dart?

Upvotes: 13

Views: 16051

Answers (3)

Rafsan Uddin Beg Rizan
Rafsan Uddin Beg Rizan

Reputation: 2297

You can use this function below if you want.

import 'dart:convert';
import 'dart:io';

  void _compress(String json) {
    final enCodedJson = utf8.encode(json);
    final gZipJson = gzip.encode(enCodedJson);
    final base64Json = base64.encode(gZipJson);

    final decodeBase64Json = base64.decode(base64Json);
    final decodegZipJson = gzip.decode(decodeBase64Json);
    final originalJson = utf8.decode(decodegZipJson);
    }

Upvotes: 26

Mayur Botre
Mayur Botre

Reputation: 1

String data=' ';
for(int i=0;i<10;i++){
    data=data+'Hello World!\r\n';
}
var original=utf8.encode(data);
var compressed=gzip.encode(original);
var decompressed=gzip.decode(compressed);

Upvotes: 0

Xavier
Xavier

Reputation: 4015

The compressed list of bytes is probably not a valid UTF8 sequence instead you could encode it in base64.

import 'dart:convert';
import 'package:archive/archive.dart';

void main() {
  var myString = 'myString';
  var stringBytes = utf8.encode(myString);
  var gzipBytes = GZipEncoder().encode(stringBytes);
  var compressedString = base64.encode(gzipBytes);

  print(compressedString);
}

Upvotes: 11

Related Questions