ShotEasy
📖 Blog - Optimizing PNG Image Compression with C++ Libraries

Optimizing PNG Image Compression with C++ Libraries

CH563
CH563
19 days ago

compress-png-using-webassembly

Using the C++ libraries libimagequant, libpng, and zlib to compress png images

PNG Image Compression Principles:

Image Preprocessing: Using filters to convert image data into a more compressible differential form.

Applying the DEFLATE Algorithm: Compressing data using LZ77 and Huffman coding.

Adding a Checksum: Ensuring data integrity with CRC verification.

To achieve the best results, you can directly use the C++ libraries libimagequant, libpng, and zlib.

libimagequant is a library for optimizing PNG images by reducing the number of colors through quantization, thereby decreasing the image size. You can use libimagequant for color quantization during the compression process.

libpng is a widely-used PNG image processing library that supports reading and writing PNG image files.

zlib is a general-purpose data compression library, and libpng typically uses zlib internally for data compression.

To use the compressed images directly on a web page, you need to compile the C++ code into WebAssembly (WASM).

Emscripten can be used to compile C/C++ code into WASM, while also generating the corresponding JavaScript code to load and call these WASM modules.

Installation of Emscripten

git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh

Exporting functions and generating files

extern "C" {
    void compressPng() {
        // 调用之前编写的压缩逻辑
    }
}
emcc main.cpp -o png_compress.js -s EXPORTED_FUNCTIONS='["_compressPng"]' -s EXTRA_EXPORTED_RUNTIME_METHODS='["FS_createDataFile", "FS_readFile"]' -lpng -lz -limagequant
Compiling code with Emscripten

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(PNGCompress)

set(CMAKE_CXX_STANDARD 11)

# 设置Emscripten工具链
set(CMAKE_TOOLCHAIN_FILE ${CMAKE_SOURCE_DIR}/path/to/emsdk/upstream/emscripten/cmake/Modules/Platform/Emscripten.cmake)

# 添加源文件
add_executable(png_compress main.cpp)

# 链接库
target_link_libraries(png_compress png z imagequant)
mkdir build
cd build
emcmake cmake ..
emmake make

This will generate a png_compress.js and png_compress.wasm file

Introducing png_compress.js in the webpage will allow you to use it

Cautions:

Emscripten toolchain path: Make sure the path to the Emscripten toolchain is set correctly in CMakeLists.txt.

Exported Functions: Export as many functions as necessary for JavaScript calls.

File system operations: Use Emscripten’s file system (FS) interface to handle file read and write operations.

Open source library ShotEasy use this corresponding WASM in the local lossless fast compression of images, compression rate of 80% or more

Batch image compression, supports JPG/JPEG/PNG/WEBP/GIF/SVG/AVIF formats.