iOS/MAC 数据压缩与解压缩及常用算法 LZMA、ZLIB

时间:2024-03-02 13:13:17

苹果提供的常用的数据压缩算法LZMA、ZLIB、LZ4等;

这三种算法也是苹果建议的,可跨平台使用;

定义如下:

    /* Commonly-available encoders */
    COMPRESSION_LZ4     = 0x100,       // available starting OS X 10.11, iOS 9.0
    COMPRESSION_ZLIB    = 0x205,       // available starting OS X 10.11, iOS 9.0
    COMPRESSION_LZMA    = 0x306,       // available starting OS X 10.11, iOS 9.0

    COMPRESSION_LZ4_RAW = 0x101,       // available starting OS X 10.11, iOS 9.0

    /* Apple-specific encoders */
    COMPRESSION_LZFSE    = 0x801,      // available starting OS X 10.11, iOS 9.0

 

适用于有大文件数据上传下载,节省流量可以考虑使用;

使用说明:

1. 需要引用头文件

#include "compression.h"

2. 数据压缩示例:

- (void)testCompress{
    
    
    NSData *src = [NSData dataWithContentsOfFile:@"/Users/cocoajin/Desktop/src.txt"];
    
    NSLog(@"src: %ld",src.length);
    
    uint8_t *dstBuffer = (uint8_t *)malloc(src.length);
    memset(dstBuffer, 0, src.length);
    
    size_t compressResultLength = compression_encode_buffer(dstBuffer, src.length, [src bytes], src.length, NULL, COMPRESSION_LZMA);
    
    if (compressResultLength > 0) {
        NSData *newData = [NSData dataWithBytes:dstBuffer length:compressResultLength];
        [newData writeToFile:@"/Users/cocoajin/Desktop/compress.data" atomically:YES];
        NSLog(@"com: %ld",compressResultLength);
        NSLog(@"com: %.2f",(src.length-compressResultLength)/(float)src.length);
        
    }else{
        NSLog(@"compress error!");
    }
    
    free(dstBuffer);
}

  

3. 数据解压缩示例:

- (void)testDeCompress{
    NSData *src = [NSData dataWithContentsOfFile:@"/Users/cocoajin/Desktop/compress.data"];
    
    NSLog(@"src: %ld",src.length);
    uint8_t *dstBuffer = (uint8_t *)malloc(1024*1024*10);
    memset(dstBuffer, 0, src.length);
    
    size_t decompressLen = compression_decode_buffer(dstBuffer,1024*1024*10,src.bytes,src.length,NULL,COMPRESSION_LZMA);
    
    if (decompressLen > 0) {
        NSData *newData = [NSData dataWithBytes:dstBuffer length:decompressLen];
        [newData writeToFile:@"/Users/cocoajin/Desktop/decompress.txt" atomically:YES];
        NSLog(@"com: %ld",decompressLen);
        
    }else{
        NSLog(@"decompressLen error!");
    }
    
    free(dstBuffer);
}

 

4. 实际测对一个1.9M的txt小说文件压缩,压缩以后大小为0.8m,压缩效果还是很明显的;