DEV Community

HarmonyOS
HarmonyOS

Posted on

How to solve the problem of incorrect output result when using zlip to compress string with gzip

Read the original article:How to solve the problem of incorrect output result when using zlip to compress string with gzip

How to solve the problem of incorrect output result when using zlip to compress string with gzip

Problem phenomenon

The binary data (Uint8Array) of the object needs to be compressed with gzip and converted to base64 output string, but after compression with zlip.compress, it is not the default output format of gzip compression to base64 output string: H4sIAAAAAAAAA************AAAA==

Background knowledge

File compression guide.

Location ideas

(1) Observe that the output result is not the default output format of gzip compression followed by Base64 string conversion.

(2) Carefully refer to the official document: zlip.compress212. The current interface uses zip compression instead of gzip compression.

(3) From the community ecosystem, check the relevant HarmonyOS third-party libraries

. In pako, a gzip compression interface is provided: pako Demo. After debugging, it can be found that the result is returned correctly.

Solution

(1) Use the third-party library pako for gzip compression:

pako demo reference address: pako Demo.
Install the third-party library dependencies: ohpm install pako.

The code example is as follows:

import { util } from '@kit.ArkTS';
import pako from 'pako'

//You need to install the third-party library dependency: ohpm install pako

import { util } from '@kit.ArkTS';
import pako from 'pako'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Text('zipcompress')
        .onClick(() => {
          pakoGizp()
        })
        .fontSize(40)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
    }
    .height('100%')
    .width('100%')
  }
}

function pakoGizp() {
  const str = 'hello world'
  const data: Uint8Array | undefined = pako.gzip(str)
  let base64 = new util.Base64Helper
  let str_zip = base64.encodeToStringSync(data);
  console.log(str_zip)
}
Enter fullscreen mode Exit fullscreen mode

Written by Emine Inan

Top comments (0)