crossbind
GitHub
← 所有库

libjpeg-turbo

高性能 JPEG 编解码器。

安装

在浏览器中运行;Node.js 和边缘运行环境也使用同一个包。构建目标:wasm32,单线程和多线程。

shell
npm install @crossbind/port-jpegturbo-wasm@beta
crossbind.config.js
import jpegturboWasm from '@crossbind/port-jpegturbo-wasm/crossbind.config.js';
 
export default {
dependencies: [jpegturboWasm],
paths: { config: import.meta.url },
};
main.js
import { initNative, jpeg_compress_struct } from '@crossbind/port-jpegturbo/jpeglib.h';
 
await initNative();

crossbind 本身随你的打包工具插件一起提供;打包工具插件介绍了 Vite、Webpack、Rspack、Rsbuild、Rollup、esbuild、Bun 和 Next.js 的用法。

在浏览器中运行 libjpeg-turbo:canvas 不提供的 JPEG 控制选项

浏览器能解码 JPEG,也能通过 canvas.toBlob 编码 JPEG,但只能设置一个质量数值。这些应用运行由 crossbind 编译的 JPEG 参考库:它们能在不重新编码的情况下去除照片中的位置和相机数据,把编码器的每项设置与当前浏览器自己的编码器并排展示,并把一张 1200 万像素的照片直接解码为缩略图。 首次运行时会下载一次 1 MB 的 WebAssembly;本页的所有应用都共用它,而且不会上传任何内容。

应用 01

看看照片泄露了什么,再在不重新编码的情况下将其移除

手机照片可能带有拍摄地点、相机序列号,以及它自己的一张预览图。这个应用会读取每个段,展示它们透露的信息,然后写出一个不含这些信息的副本。图像数据是逐个系数复制的,而不是重新编码,所以副本的每个像素都完全相同;页面会把两者都解码出来加以证明。

示例在模块中生成,使用一台虚构的相机和一个公共地标的坐标。你自己的照片只保留在这个标签页中:它会被挂载到模块的内存文件系统中,绝不会上传。

打开示例,或者你手机中的 JPEG,看看它的元数据透露了什么。
查看代码
src/native/jpeg_scrub.h
// src/native/jpeg_scrub.h (excerpt): the image is copied, never re-encoded
jvirt_barray_ptr* coefficients = jpeg_read_coefficients(&source.cinfo);
jpeg_copy_critical_parameters(&source.cinfo, &target.cinfo);
target.cinfo.optimize_coding = optimize ? TRUE : FALSE;
if (progressive) jpeg_simple_progression(&target.cinfo);
jpeg_write_coefficients(&target.cinfo, coefficients);
if (keepOrientation && orientation > 1) {
const std::string block = exif::orientationOnly(orientation);
jpeg_write_marker(&target.cinfo, JPEG_APP0 + 1,
reinterpret_cast<const JOCTET*>(block.data()), block.size());
}
// the ICC profile's APP2 segments follow when keepProfile; every
// other APPn and COM segment of the original stays behind
jpeg_finish_compress(&target.cinfo);
main.js
const m = await initNative();
const [path] = await m.autoMountFiles([file], await m.getRandomPath('/memfs')); // the dropped photo
const report = JSON.parse(await m.JpegScrub.inspect(path));
// report.exif.gps: { lat, lon, alt }; report.segments: [{ marker, label, bytes }]
 
await m.FS.mkdirTree('/memfs/out');
const done = JSON.parse(await m.JpegScrub.clean(path, '/memfs/out/clean.jpg', true, true, true, false));
const proof = JSON.parse(await m.JpegScrub.compare(path, '/memfs/out/clean.jpg'));
// the sample: 123,613 B before, 106,361 B after, proof.differing 0
应用 02

canvas.toBlob 不提供的 JPEG 设置

canvas.toBlob('image/jpeg', quality) 只接受一个数字,每个浏览器都会把它映射到自己的编码器上。在这里,同样的像素经过 libjpeg-turbo 编码,所有设置都由你决定:质量、色度子采样(chroma subsampling)、渐进式扫描、优化的 Huffman 表和算术编码。每个结果都会以字节数和 PSNR 衡量,并与这个浏览器的 toBlob 在相同质量下生成的结果并排比较。

示例是模块绘制的一个 960×640 的场景。你的照片会被直接解码为每边最多 1600 像素,并且只保留在这个标签页中。首次运行之后,每次更改都会重新编码。

编码示例或你的照片,查看每种设置下的字节数、PSNR 和放大的裁剪区域。
查看代码
src/native/jpeg_lab.h
// src/native/jpeg_lab.h (excerpt): every setting is a field on the compressor
jpeg_set_defaults(&encoder.cinfo);
jpeg_set_quality(&encoder.cinfo, quality, TRUE);
encoder.cinfo.comp_info[0].h_samp_factor = subsampling == 444 ? 1 : 2;
encoder.cinfo.comp_info[0].v_samp_factor = subsampling == 420 ? 2 : 1;
encoder.cinfo.optimize_coding = optimize ? TRUE : FALSE;
encoder.cinfo.arith_code = arithmetic ? TRUE : FALSE;
if (progressive) jpeg_simple_progression(&encoder.cinfo);
jpeg_start_compress(&encoder.cinfo, TRUE);
main.js
const m = await initNative();
const lab = await new m.JpegLab();
await lab.useSample(960, 640); // or lab.load(path, 1600) for a dropped photo
await m.FS.mkdirTree('/memfs/out');
 
const q75 = JSON.parse(await lab.encode(75, 420, false, false, false, '/memfs/out/a.jpg', ''));
const full = JSON.parse(await lab.encode(75, 444, false, false, false, '/memfs/out/b.jpg', ''));
// q75: 59,481 B at 31.40 dB; full colour detail: 74,930 B at 36.06 dB
应用 03

把 1200 万像素的照片直接解码成缩略图

在解码前设置 scale_denom,libjpeg-turbo 就会对每个 8×8 块执行更小的逆 DCT,所以 1/8 的缩略图会直接按它自己的尺寸解码,而不是先完整解码再缩小。这里的每个数字都是在这个标签页中测得的:同一个文件分别以 1/1、1/2、1/4 和 1/8 解码。熵解码在每种比例下的开销都相同,所以缩略图能节省多少取决于文件本身。

示例是一个 4032×3024 的场景,也就是 1200 万像素手机相机拍出的尺寸,在模块中以质量 85 编码。每种比例都解码三次,取最快的一次。

解码示例或你的照片,为每种比例计时。
查看代码
src/native/jpeg_thumbs.h
// src/native/jpeg_thumbs.h (excerpt): scale before decoding, not after
jpeg_read_header(&decoder.cinfo, TRUE);
decoder.cinfo.scale_num = 1;
decoder.cinfo.scale_denom = denominator; // 1, 2, 4 or 8
decoder.cinfo.out_color_space = JCS_EXT_RGBA;
jpeg_start_decompress(&decoder.cinfo); // output_width: image_width / denominator, rounded up
while (decoder.cinfo.output_scanline < decoder.cinfo.output_height) {
JSAMPROW row = reinterpret_cast<JSAMPROW>(&rgba[decoder.cinfo.output_scanline * stride]);
jpeg_read_scanlines(&decoder.cinfo, &row, 1);
}
main.js
const m = await initNative();
await m.FS.mkdirTree('/memfs/out');
await m.ThumbnailBench.writeSample('/memfs/out/photo.jpg'); // 4032x3024, 1,289,719 B
 
const thumb = JSON.parse(await m.ThumbnailBench.decode('/memfs/out/photo.jpg', 8, 3, '/memfs/out/thumb.rgba'));
// thumb.width 504, thumb.height 378: 762,048 B of RGBA instead of 48,771,072 B
const rgba = await m.getFileBytes('/memfs/out/thumb.rgba');

示例

每个示例都由一个小小的 C++ 头文件和调用它的 JavaScript 组成,并附有构建本站时它输出的内容。仅 JavaScript 标签页直接使用 libjpeg-turbo 自己的头文件完成同样的事,不需要 C++ 文件。最后一个是为 WASI 构建的完整 C++ 程序。

把像素编码为 JPEG

jpeg_mem_dest 把文件写入内存;jpeg_set_quality 和亮度采样因子决定了它保留多少细节。

src/native/jpeg_encoder.h
#pragma once
 
#include <cstdio>
#include <cstdlib>
#include <jpeglib.h>
 
#include <stdexcept>
#include <string>
 
// Pixels in, a JPEG file out, both in memory. Bytes cross the binding as a byte string: one UTF-16
// code unit (0-255) per byte.
class JpegEncoder {
public:
static std::string version() {
const int number = LIBJPEG_TURBO_VERSION_NUMBER;
return std::to_string(number / 1000000) + "." + std::to_string(number / 1000 % 1000) + "." + std::to_string(number % 1000);
}
 
// rgba holds width * height * 4 bytes. subsampling is 444, 422 or 420: the chroma resolution
// kept for each 2x2 block of pixels (all of it, half, a quarter).
static std::u16string encode(const std::u16string& rgba, int width, int height, int quality, int subsampling) {
if (width < 1 || height < 1 || rgba.size() != static_cast<size_t>(width) * height * 4) throw std::invalid_argument("rgba must hold width * height * 4 bytes");
if (quality < 1 || quality > 100) throw std::invalid_argument("quality must be between 1 and 100");
if (subsampling != 444 && subsampling != 422 && subsampling != 420) throw std::invalid_argument("subsampling must be 444, 422 or 420");
std::string pixels(rgba.size(), '\0');
for (size_t i = 0; i < rgba.size(); ++i) {
if (rgba[i] > 0xFF) throw std::invalid_argument("not a byte string");
pixels[i] = static_cast<char>(rgba[i]);
}
 
Compressor jpeg;
unsigned char* buffer = nullptr;
unsigned long size = 0;
jpeg_mem_dest(&jpeg.cinfo, &buffer, &size);
jpeg.cinfo.image_width = static_cast<JDIMENSION>(width);
jpeg.cinfo.image_height = static_cast<JDIMENSION>(height);
jpeg.cinfo.input_components = 4;
jpeg.cinfo.in_color_space = JCS_EXT_RGBA;
jpeg_set_defaults(&jpeg.cinfo);
jpeg_set_quality(&jpeg.cinfo, quality, TRUE);
jpeg.cinfo.comp_info[0].h_samp_factor = subsampling == 444 ? 1 : 2;
jpeg.cinfo.comp_info[0].v_samp_factor = subsampling == 420 ? 2 : 1;
jpeg_start_compress(&jpeg.cinfo, TRUE);
while (jpeg.cinfo.next_scanline < jpeg.cinfo.image_height) {
JSAMPROW row = reinterpret_cast<JSAMPROW>(&pixels[static_cast<size_t>(jpeg.cinfo.next_scanline) * width * 4]);
jpeg_write_scanlines(&jpeg.cinfo, &row, 1);
}
// jpeg_mem_dest reallocates as the file grows and hands the final buffer over only here.
jpeg_finish_compress(&jpeg.cinfo);
std::u16string file(buffer, buffer + size);
std::free(buffer);
return file;
}
 
private:
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] static void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Compressor {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
Compressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_compress(&cinfo);
}
~Compressor() { jpeg_destroy_compress(&cinfo); }
Compressor(const Compressor&) = delete;
Compressor& operator=(const Compressor&) = delete;
};
};
main.js
import { initNative, JpegEncoder } from './native/jpeg_encoder.h';
 
await initNative();
const [width, height] = [100, 75];
const rgba = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i += 1) {
const [x, y] = [i % width, Math.floor(i / width)];
const disc = (x - 50) ** 2 + (y - 37) ** 2 < 400;
rgba.set(disc ? [230, 30, 40, 255] : [x * 2, y * 3, 160, 255], i * 4);
}
const pixels = String.fromCharCode(...rgba);
console.log(`libjpeg-turbo ${await JpegEncoder.version()}: ${width}x${height}, ${rgba.length} B of RGBA`);
for (const [quality, subsampling] of [[90, 444], [90, 420], [50, 420]]) {
const jpeg = await JpegEncoder.encode(pixels, width, height, quality, subsampling);
console.log(`quality ${quality}, subsampling ${subsampling}: ${jpeg.length} B`);
}
输出首次运行需下载 1 MB
libjpeg-turbo 3.2.1: 100x75, 30000 B of RGBA
quality 90, subsampling 444: 2791 B
quality 90, subsampling 420: 1932 B
quality 50, subsampling 420: 1171 B

解码 JPEG 并读取文件头

jpeg_mem_src 从内存中读取文件:在解码任何像素之前,jpeg_read_header 就能告诉你这是一幅什么样的图像,jpeg_read_scanlines 则把它解码为 RGBA。libjpeg-turbo 无法读取的文件会抛出它的错误消息。

src/native/jpeg_decoder.h
#pragma once
 
#include <cstdio>
#include <jpeglib.h>
 
#include <stdexcept>
#include <string>
 
// A JPEG file in memory to RGBA pixels, and what its header says. A file libjpeg-turbo cannot read
// throws libjpeg's own message instead of ending the program.
class JpegDecoder {
public:
// {"width","height","components","colorSpace","progressive"}, read without decoding a pixel.
static std::string header(const std::u16string& jpeg) {
const std::string file = toBytes(jpeg);
Decompressor decoder;
jpeg_mem_src(&decoder.cinfo, reinterpret_cast<const unsigned char*>(file.data()), file.size());
jpeg_read_header(&decoder.cinfo, TRUE);
const jpeg_decompress_struct& info = decoder.cinfo;
return "{\"width\":" + std::to_string(info.image_width) + ",\"height\":" + std::to_string(info.image_height) +
",\"components\":" + std::to_string(info.num_components) + ",\"colorSpace\":\"" + colorSpace(info.jpeg_color_space) +
"\",\"progressive\":" + (jpeg_has_multiple_scans(&decoder.cinfo) ? "true" : "false") + "}";
}
 
// width * height * 4 bytes of RGBA; greyscale files come out with R = G = B.
static std::u16string decode(const std::u16string& jpeg) {
const std::string file = toBytes(jpeg);
Decompressor decoder;
jpeg_mem_src(&decoder.cinfo, reinterpret_cast<const unsigned char*>(file.data()), file.size());
jpeg_read_header(&decoder.cinfo, TRUE);
decoder.cinfo.out_color_space = JCS_EXT_RGBA;
jpeg_start_decompress(&decoder.cinfo);
const size_t stride = static_cast<size_t>(decoder.cinfo.output_width) * 4;
std::u16string rgba(stride * decoder.cinfo.output_height, u'\0');
std::string row(stride, '\0');
while (decoder.cinfo.output_scanline < decoder.cinfo.output_height) {
const size_t y = decoder.cinfo.output_scanline;
JSAMPROW pointer = reinterpret_cast<JSAMPROW>(&row[0]);
jpeg_read_scanlines(&decoder.cinfo, &pointer, 1);
for (size_t x = 0; x < stride; ++x) rgba[y * stride + x] = static_cast<unsigned char>(row[x]);
}
jpeg_finish_decompress(&decoder.cinfo);
return rgba;
}
 
private:
static std::string toBytes(const std::u16string& units) {
std::string bytes(units.size(), '\0');
for (size_t i = 0; i < units.size(); ++i) {
if (units[i] > 0xFF) throw std::invalid_argument("not a byte string");
bytes[i] = static_cast<char>(units[i]);
}
return bytes;
}
 
static const char* colorSpace(J_COLOR_SPACE space) {
switch (space) {
case JCS_GRAYSCALE: return "greyscale";
case JCS_RGB: return "RGB";
case JCS_YCbCr: return "YCbCr";
case JCS_CMYK: return "CMYK";
case JCS_YCCK: return "YCCK";
default: return "unknown";
}
}
 
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] static void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Decompressor {
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
Decompressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_decompress(&cinfo);
}
~Decompressor() { jpeg_destroy_decompress(&cinfo); }
Decompressor(const Decompressor&) = delete;
Decompressor& operator=(const Decompressor&) = delete;
};
};
main.js
import { initNative, JpegDecoder } from './native/jpeg_decoder.h';
import { JpegEncoder } from './native/jpeg_encoder.h';
 
await initNative();
const [width, height] = [100, 75];
const rgba = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i += 1) {
const [x, y] = [i % width, Math.floor(i / width)];
const disc = (x - 50) ** 2 + (y - 37) ** 2 < 400;
rgba.set(disc ? [230, 30, 40, 255] : [x * 2, y * 3, 160, 255], i * 4);
}
const jpeg = await JpegEncoder.encode(String.fromCharCode(...rgba), width, height, 90, 420); // the first example's encoder
 
const info = JSON.parse(await JpegDecoder.header(jpeg));
console.log(`${info.width}x${info.height}, ${info.components} components, ${info.colorSpace}, ${info.progressive ? 'progressive' : 'baseline'}`);
const decoded = Uint8Array.from(await JpegDecoder.decode(jpeg), (c) => c.charCodeAt(0));
const at = (10 * width + 10) * 4;
console.log(`${decoded.length} B of RGBA; pixel (10, 10) was ${rgba.slice(at, at + 4)} and decodes as ${decoded.slice(at, at + 4)}`);
try {
await JpegDecoder.decode('crossbind');
} catch (error) {
console.log(error.message);
}
输出首次运行需下载 1 MB
100x75, 3 components, YCbCr, baseline
30000 B of RGBA; pixel (10, 10) was 20,30,160,255 and decodes as 22,29,159,255
std::runtime_error: Not a JPEG file: starts with 0x63 0x72

直接解码为缩略图

在解码前设置 scale_num 和 scale_denom,libjpeg-turbo 就会对每个块执行更小的逆 DCT:按 1/8 解码时,根本不会构建全尺寸图像。

src/native/jpeg_thumbnail.h
#pragma once
 
#include <cstdio>
#include <jpeglib.h>
 
#include <stdexcept>
#include <string>
 
// Decodes straight to a smaller image: with scale_num / scale_denom set, libjpeg-turbo runs a
// smaller inverse DCT on every 8x8 block, so a 1/8 thumbnail never exists at full size.
class JpegThumbnail {
public:
// The size a decode at 1/denominator produces, "WxH"; each side rounds up.
static std::string size(const std::u16string& jpeg, int denominator) {
const std::string file = toBytes(jpeg);
Decompressor decoder;
open(decoder, file, denominator);
jpeg_calc_output_dimensions(&decoder.cinfo);
return std::to_string(decoder.cinfo.output_width) + "x" + std::to_string(decoder.cinfo.output_height);
}
 
// RGBA pixels of the decode at 1/denominator (1, 2, 4 or 8).
static std::u16string decode(const std::u16string& jpeg, int denominator) {
const std::string file = toBytes(jpeg);
Decompressor decoder;
open(decoder, file, denominator);
decoder.cinfo.out_color_space = JCS_EXT_RGBA;
jpeg_start_decompress(&decoder.cinfo);
const size_t stride = static_cast<size_t>(decoder.cinfo.output_width) * 4;
std::string rgba(stride * decoder.cinfo.output_height, '\0');
while (decoder.cinfo.output_scanline < decoder.cinfo.output_height) {
JSAMPROW row = reinterpret_cast<JSAMPROW>(&rgba[decoder.cinfo.output_scanline * stride]);
jpeg_read_scanlines(&decoder.cinfo, &row, 1);
}
jpeg_finish_decompress(&decoder.cinfo);
return std::u16string(rgba.begin(), rgba.end());
}
 
private:
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] static void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Decompressor {
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
Decompressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_decompress(&cinfo);
}
~Decompressor() { jpeg_destroy_decompress(&cinfo); }
Decompressor(const Decompressor&) = delete;
Decompressor& operator=(const Decompressor&) = delete;
};
 
static void open(Decompressor& decoder, const std::string& file, int denominator) {
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) throw std::invalid_argument("denominator must be 1, 2, 4 or 8");
jpeg_mem_src(&decoder.cinfo, reinterpret_cast<const unsigned char*>(file.data()), file.size());
jpeg_read_header(&decoder.cinfo, TRUE);
decoder.cinfo.scale_num = 1;
decoder.cinfo.scale_denom = static_cast<unsigned int>(denominator);
}
 
static std::string toBytes(const std::u16string& units) {
std::string bytes(units.size(), '\0');
for (size_t i = 0; i < units.size(); ++i) {
if (units[i] > 0xFF) throw std::invalid_argument("not a byte string");
bytes[i] = static_cast<char>(units[i]);
}
return bytes;
}
};
main.js
import { initNative, JpegThumbnail } from './native/jpeg_thumbnail.h';
import { JpegEncoder } from './native/jpeg_encoder.h';
 
await initNative();
const [width, height] = [100, 75];
const rgba = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i += 1) {
const [x, y] = [i % width, Math.floor(i / width)];
const disc = (x - 50) ** 2 + (y - 37) ** 2 < 400;
rgba.set(disc ? [230, 30, 40, 255] : [x * 2, y * 3, 160, 255], i * 4);
}
const jpeg = await JpegEncoder.encode(String.fromCharCode(...rgba), width, height, 90, 420); // the first example's encoder
 
for (const denominator of [1, 2, 4, 8]) {
console.log(`1/${denominator}: ${await JpegThumbnail.size(jpeg, denominator)}`);
}
const thumbnail = await JpegThumbnail.decode(jpeg, 8);
console.log(`${thumbnail.length} B of RGBA instead of ${rgba.length} B`);
输出首次运行需下载 1 MB
1/1: 100x75
1/2: 50x38
1/4: 25x19
1/8: 13x10
520 B of RGBA instead of 30000 B

不重新编码就缩小 JPEG

jpeg_read_coefficients 和 jpeg_write_coefficients 像 jpegtran -copy all 那样,把量化后的 DCT 系数从一个文件复制到另一个文件:只重做 Huffman 编码(优化编码或渐进式),每个像素都保持不变。

src/native/jpeg_transcode.h
#pragma once
 
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <jpeglib.h>
 
#include <stdexcept>
#include <string>
 
// Rewrites a JPEG without decoding it to pixels, as `jpegtran -copy all` does: the quantised DCT
// coefficients are copied as they are, so no quality is lost. Only their entropy coding changes.
class JpegTranscoder {
public:
// optimize: Huffman tables fitted to this image instead of the standard ones.
// progressive: scans that draw a coarse image first; libjpeg-turbo optimises those tables anyway.
static std::u16string transcode(const std::u16string& jpeg, bool optimize, bool progressive) {
const std::string file = toBytes(jpeg);
Decompressor source;
jpeg_mem_src(&source.cinfo, reinterpret_cast<const unsigned char*>(file.data()), file.size());
jpeg_save_markers(&source.cinfo, JPEG_COM, 0xFFFF);
for (int app = 0; app < 16; ++app) jpeg_save_markers(&source.cinfo, JPEG_APP0 + app, 0xFFFF);
jpeg_read_header(&source.cinfo, TRUE);
jvirt_barray_ptr* coefficients = jpeg_read_coefficients(&source.cinfo);
 
Compressor target;
unsigned char* buffer = nullptr;
unsigned long size = 0;
jpeg_mem_dest(&target.cinfo, &buffer, &size);
jpeg_copy_critical_parameters(&source.cinfo, &target.cinfo);
target.cinfo.optimize_coding = optimize ? TRUE : FALSE;
if (progressive) jpeg_simple_progression(&target.cinfo);
jpeg_write_coefficients(&target.cinfo, coefficients);
for (jpeg_saved_marker_ptr marker = source.cinfo.marker_list; marker != nullptr; marker = marker->next) {
// The library writes its own JFIF and Adobe segments; copying the old ones would duplicate them.
if (target.cinfo.write_JFIF_header && marker->marker == JPEG_APP0 && startsWith(marker, "JFIF", 5)) continue;
if (target.cinfo.write_Adobe_marker && marker->marker == JPEG_APP0 + 14 && startsWith(marker, "Adobe", 5)) continue;
jpeg_write_marker(&target.cinfo, marker->marker, marker->data, marker->data_length);
}
// jpeg_mem_dest reallocates as the file grows and hands the final buffer over only here.
jpeg_finish_compress(&target.cinfo);
jpeg_finish_decompress(&source.cinfo);
std::u16string out(buffer, buffer + size);
std::free(buffer);
return out;
}
 
private:
static bool startsWith(jpeg_saved_marker_ptr marker, const char* id, unsigned int length) {
return marker->data_length >= length && std::memcmp(marker->data, id, length) == 0;
}
 
static std::string toBytes(const std::u16string& units) {
std::string bytes(units.size(), '\0');
for (size_t i = 0; i < units.size(); ++i) {
if (units[i] > 0xFF) throw std::invalid_argument("not a byte string");
bytes[i] = static_cast<char>(units[i]);
}
return bytes;
}
 
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] static void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Decompressor {
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
Decompressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_decompress(&cinfo);
}
~Decompressor() { jpeg_destroy_decompress(&cinfo); }
Decompressor(const Decompressor&) = delete;
Decompressor& operator=(const Decompressor&) = delete;
};
 
struct Compressor {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
Compressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_compress(&cinfo);
}
~Compressor() { jpeg_destroy_compress(&cinfo); }
Compressor(const Compressor&) = delete;
Compressor& operator=(const Compressor&) = delete;
};
};
main.js
import { initNative, JpegTranscoder } from './native/jpeg_transcode.h';
import { JpegEncoder } from './native/jpeg_encoder.h';
import { JpegDecoder } from './native/jpeg_decoder.h';
 
await initNative();
const [width, height] = [100, 75];
const rgba = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i += 1) {
const [x, y] = [i % width, Math.floor(i / width)];
const disc = (x - 50) ** 2 + (y - 37) ** 2 < 400;
rgba.set(disc ? [230, 30, 40, 255] : [x * 2, y * 3, 160, 255], i * 4);
}
const jpeg = await JpegEncoder.encode(String.fromCharCode(...rgba), width, height, 90, 420); // the first example's encoder
 
const optimized = await JpegTranscoder.transcode(jpeg, true, false);
const progressive = await JpegTranscoder.transcode(jpeg, false, true);
console.log(`baseline ${jpeg.length} B, optimized ${optimized.length} B, progressive ${progressive.length} B`);
const pixels = await JpegDecoder.decode(jpeg); // the second example's decoder
console.log((await JpegDecoder.decode(optimized)) === pixels && (await JpegDecoder.decode(progressive)) === pixels);
输出首次运行需下载 1 MB
baseline 1932 B, optimized 1512 B, progressive 1773 B
true

读写 EXIF 和注释

jpeg_save_markers 会保留 libjpeg-turbo 原本会跳过的 APPn 和 COM 段,jpeg_write_marker 则会添加新的段。这里在不重新编码图像的情况下,写入了一个 EXIF 方向和一条注释。

src/native/jpeg_markers.h
#pragma once
 
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <jpeglib.h>
 
#include <stdexcept>
#include <string>
 
// APPn and COM segments carry everything that is not the image: EXIF (APP1), ICC profiles (APP2),
// XMP, comments. libjpeg-turbo skips them unless asked: jpeg_save_markers keeps them for reading,
// jpeg_write_marker adds new ones.
class JpegMarkers {
public:
// Sets the EXIF orientation (1-8) and a comment without re-encoding: the coefficients are copied,
// and every other segment is kept.
static std::u16string tag(const std::u16string& jpeg, int orientation, const std::string& comment) {
if (orientation < 1 || orientation > 8) throw std::invalid_argument("orientation must be between 1 and 8");
const std::string file = toBytes(jpeg);
Decompressor source;
open(source, file);
jvirt_barray_ptr* coefficients = jpeg_read_coefficients(&source.cinfo);
 
Compressor target;
unsigned char* buffer = nullptr;
unsigned long size = 0;
jpeg_mem_dest(&target.cinfo, &buffer, &size);
jpeg_copy_critical_parameters(&source.cinfo, &target.cinfo);
jpeg_write_coefficients(&target.cinfo, coefficients);
const std::string exif = exifWithOrientation(orientation);
jpeg_write_marker(&target.cinfo, JPEG_APP0 + 1, reinterpret_cast<const JOCTET*>(exif.data()), static_cast<unsigned int>(exif.size()));
for (jpeg_saved_marker_ptr marker = source.cinfo.marker_list; marker != nullptr; marker = marker->next) {
if (marker->marker == JPEG_COM || (marker->marker == JPEG_APP0 + 1 && startsWith(marker, "Exif\0", 6))) continue; // replaced
if (target.cinfo.write_JFIF_header && marker->marker == JPEG_APP0 && startsWith(marker, "JFIF", 5)) continue; // written by the library
jpeg_write_marker(&target.cinfo, marker->marker, marker->data, marker->data_length);
}
jpeg_write_marker(&target.cinfo, JPEG_COM, reinterpret_cast<const JOCTET*>(comment.data()), static_cast<unsigned int>(comment.size()));
// jpeg_mem_dest reallocates as the file grows and hands the final buffer over only here.
jpeg_finish_compress(&target.cinfo);
jpeg_finish_decompress(&source.cinfo);
std::u16string out(buffer, buffer + size);
std::free(buffer);
return out;
}
 
// {"markers":[{"marker":"APP1","label":"Exif","bytes":32},...],"orientation":6,"comment":"..."}:
// every APPn and COM segment in file order (a COM has no label), the EXIF orientation (0 when
// there is none) and the first comment.
static std::string read(const std::u16string& jpeg) {
const std::string file = toBytes(jpeg);
Decompressor decoder;
open(decoder, file);
std::string markers;
int orientation = 0;
std::string comment;
bool hasComment = false;
for (jpeg_saved_marker_ptr marker = decoder.cinfo.marker_list; marker != nullptr; marker = marker->next) {
const bool com = marker->marker == JPEG_COM;
if (com && !hasComment) {
comment.assign(reinterpret_cast<const char*>(marker->data), marker->data_length);
hasComment = true;
}
if (marker->marker == JPEG_APP0 + 1 && startsWith(marker, "Exif\0", 6) && orientation == 0) orientation = exifOrientation(marker);
markers += std::string(markers.empty() ? "" : ",") + "{\"marker\":\"" + (com ? std::string("COM") : "APP" + std::to_string(marker->marker - JPEG_APP0)) +
"\",\"label\":\"" + label(marker) + "\",\"bytes\":" + std::to_string(marker->data_length) + "}";
}
return "{\"markers\":[" + markers + "],\"orientation\":" + std::to_string(orientation) + ",\"comment\":" + jsonString(comment) + "}";
}
 
private:
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] static void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Decompressor {
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
Decompressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_decompress(&cinfo);
}
~Decompressor() { jpeg_destroy_decompress(&cinfo); }
Decompressor(const Decompressor&) = delete;
Decompressor& operator=(const Decompressor&) = delete;
};
 
struct Compressor {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
Compressor() {
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_compress(&cinfo);
}
~Compressor() { jpeg_destroy_compress(&cinfo); }
Compressor(const Compressor&) = delete;
Compressor& operator=(const Compressor&) = delete;
};
 
// Reads the header and keeps every APPn and COM segment.
static void open(Decompressor& decoder, const std::string& file) {
jpeg_mem_src(&decoder.cinfo, reinterpret_cast<const unsigned char*>(file.data()), file.size());
jpeg_save_markers(&decoder.cinfo, JPEG_COM, 0xFFFF);
for (int app = 0; app < 16; ++app) jpeg_save_markers(&decoder.cinfo, JPEG_APP0 + app, 0xFFFF);
jpeg_read_header(&decoder.cinfo, TRUE);
}
 
static const char* label(jpeg_saved_marker_ptr marker) {
if (marker->marker == JPEG_COM) return "";
if (marker->marker == JPEG_APP0 && startsWith(marker, "JFIF", 5)) return "JFIF";
if (marker->marker == JPEG_APP0 + 1 && startsWith(marker, "Exif\0", 6)) return "Exif";
if (marker->marker == JPEG_APP0 + 1 && startsWith(marker, "http://ns.adobe.com/xap/1.0/", 29)) return "XMP";
if (marker->marker == JPEG_APP0 + 2 && startsWith(marker, "ICC_PROFILE", 12)) return "ICC profile";
if (marker->marker == JPEG_APP0 + 14 && startsWith(marker, "Adobe", 5)) return "Adobe";
return "unknown";
}
 
static bool startsWith(jpeg_saved_marker_ptr marker, const char* id, unsigned int length) {
return marker->data_length >= length && std::memcmp(marker->data, id, length) == 0;
}
 
// "Exif\0\0", then a big-endian TIFF header and one IFD holding tag 0x0112 (Orientation, SHORT).
static std::string exifWithOrientation(int orientation) {
const unsigned char bytes[] = {'E', 'x', 'i', 'f', 0, 0, 'M', 'M', 0, 42, 0, 0, 0, 8, 0, 1, 0x01, 0x12, 0, 3, 0, 0, 0, 1,
0, static_cast<unsigned char>(orientation), 0, 0, 0, 0, 0, 0};
return std::string(reinterpret_cast<const char*>(bytes), sizeof(bytes));
}
 
// Reads Orientation from IFD0 of an EXIF segment, in either TIFF byte order; 0 when it is absent.
static int exifOrientation(jpeg_saved_marker_ptr marker) {
const unsigned char* tiff = marker->data + 6;
const size_t length = marker->data_length - 6;
if (length < 8) return 0;
const bool little = tiff[0] == 'I';
const auto read16 = [&](size_t at) { return little ? tiff[at] | tiff[at + 1] << 8 : tiff[at] << 8 | tiff[at + 1]; };
const auto read32 = [&](size_t at) { return static_cast<size_t>(read16(little ? at + 2 : at)) << 16 | static_cast<size_t>(read16(little ? at : at + 2)); };
const size_t ifd = read32(4);
if (ifd + 2 > length) return 0;
const size_t count = static_cast<size_t>(read16(ifd));
for (size_t entry = 0; entry < count && ifd + 2 + entry * 12 + 12 <= length; ++entry) {
const size_t at = ifd + 2 + entry * 12;
if (read16(at) == 0x0112) return read16(at + 8);
}
return 0;
}
 
static std::string jsonString(const std::string& text) {
std::string out = "\"";
for (const unsigned char c : text) {
if (c == '"' || c == '\\') {
out += '\\';
out += static_cast<char>(c);
} else if (c < 0x20) {
char escaped[8];
std::snprintf(escaped, sizeof(escaped), "\\u%04x", c);
out += escaped;
} else {
out += static_cast<char>(c);
}
}
return out + "\"";
}
 
static std::string toBytes(const std::u16string& units) {
std::string bytes(units.size(), '\0');
for (size_t i = 0; i < units.size(); ++i) {
if (units[i] > 0xFF) throw std::invalid_argument("not a byte string");
bytes[i] = static_cast<char>(units[i]);
}
return bytes;
}
};
main.js
import { initNative, JpegMarkers } from './native/jpeg_markers.h';
import { JpegEncoder } from './native/jpeg_encoder.h';
 
await initNative();
const [width, height] = [100, 75];
const rgba = new Uint8Array(width * height * 4);
for (let i = 0; i < width * height; i += 1) {
const [x, y] = [i % width, Math.floor(i / width)];
const disc = (x - 50) ** 2 + (y - 37) ** 2 < 400;
rgba.set(disc ? [230, 30, 40, 255] : [x * 2, y * 3, 160, 255], i * 4);
}
const jpeg = await JpegEncoder.encode(String.fromCharCode(...rgba), width, height, 90, 420); // the first example's encoder
 
const tagged = await JpegMarkers.tag(jpeg, 6, 'made with crossbind');
const info = JSON.parse(await JpegMarkers.read(tagged));
console.log(info.markers.map(({ marker, label, bytes }) => [marker, label, `${bytes} B`].filter(Boolean).join(' ')).join(', '));
console.log(`orientation ${info.orientation}, comment "${info.comment}", ${tagged.length - jpeg.length} B added`);
输出首次运行需下载 1 MB
APP0 JFIF 14 B, APP1 Exif 32 B, COM 19 B
orientation 6, comment "made with crossbind", 59 B added

JPEG 命令行工具

WASI 没有 JavaScript 绑定:程序就是一个链接了该库的 main(),构建成一个 .wasm,再用 wasmtime 运行。这个程序按选定的质量编码 PPM,并利用 DCT 缩放生成缩略图,直接以 1/8 的尺寸解码照片。

crossbind.config.js
import jpegturboWasi from '@crossbind/port-jpegturbo-wasi/crossbind.config.js';
 
export default {
general: { name: 'jpeg-tool' },
dependencies: [jpegturboWasi],
paths: { config: import.meta.url },
};
src/native/main.cpp
// A command-line JPEG tool for WASI:
// jpeg-tool encode <input.ppm> <output.jpg> [quality]
// jpeg-tool thumbnail <input.jpg> <output.jpg> <1|2|4|8> [quality]
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <jpeglib.h>
 
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
 
namespace {
 
using File = std::unique_ptr<FILE, int (*)(FILE*)>;
 
File open(const char* path, const char* mode) {
File file(std::fopen(path, mode), std::fclose);
if (!file) throw std::runtime_error(std::string("cannot open ") + path);
return file;
}
 
// libjpeg's default error handler ends the process; this one throws libjpeg's message instead.
[[noreturn]] void throwError(j_common_ptr cinfo) {
char message[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo, message);
throw std::runtime_error(message);
}
 
struct Image {
int width = 0;
int height = 0;
std::vector<unsigned char> rgb;
};
 
// Binary PPM (P6) with 8-bit samples, as cjpeg reads it and djpeg -ppm writes it.
Image readPpm(const char* path) {
File in = open(path, "rb");
const auto number = [&]() {
int c = std::fgetc(in.get());
while (c == '#' || c == ' ' || c == '\n' || c == '\r' || c == '\t') {
if (c == '#') while (c != '\n' && c != EOF) c = std::fgetc(in.get());
c = std::fgetc(in.get());
}
int value = 0;
if (c < '0' || c > '9') throw std::runtime_error("not a binary PPM file");
while (c >= '0' && c <= '9') {
value = value * 10 + (c - '0');
c = std::fgetc(in.get());
}
return value;
};
if (std::fgetc(in.get()) != 'P' || std::fgetc(in.get()) != '6') throw std::runtime_error("not a binary PPM file (P6)");
Image image;
image.width = number();
image.height = number();
if (number() != 255) throw std::runtime_error("only 8-bit PPM files are supported");
if (image.width < 1 || image.height < 1 || image.width > 65500 || image.height > 65500) throw std::runtime_error("unsupported PPM size");
image.rgb.resize(static_cast<size_t>(image.width) * image.height * 3);
if (std::fread(image.rgb.data(), 1, image.rgb.size(), in.get()) != image.rgb.size()) throw std::runtime_error("the PPM file is truncated");
return image;
}
 
long writeJpeg(const Image& image, const char* path, int quality) {
jpeg_compress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_compress(&cinfo);
std::unique_ptr<jpeg_compress_struct, void (*)(jpeg_compress_struct*)> guard(&cinfo, jpeg_destroy_compress);
File out = open(path, "wb");
jpeg_stdio_dest(&cinfo, out.get());
cinfo.image_width = static_cast<JDIMENSION>(image.width);
cinfo.image_height = static_cast<JDIMENSION>(image.height);
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress(&cinfo, TRUE);
while (cinfo.next_scanline < cinfo.image_height) {
JSAMPROW row = const_cast<JSAMPROW>(&image.rgb[static_cast<size_t>(cinfo.next_scanline) * image.width * 3]);
jpeg_write_scanlines(&cinfo, &row, 1);
}
jpeg_finish_compress(&cinfo);
return std::ftell(out.get());
}
 
// Decodes at 1/denominator: libjpeg-turbo runs a smaller inverse DCT on every block.
Image readJpeg(const char* path, int denominator, int& fullWidth, int& fullHeight) {
File in = open(path, "rb");
jpeg_decompress_struct cinfo;
jpeg_error_mgr jerr;
cinfo.err = jpeg_std_error(&jerr);
jerr.error_exit = throwError;
jpeg_create_decompress(&cinfo);
std::unique_ptr<jpeg_decompress_struct, void (*)(jpeg_decompress_struct*)> guard(&cinfo, jpeg_destroy_decompress);
jpeg_stdio_src(&cinfo, in.get());
jpeg_read_header(&cinfo, TRUE);
fullWidth = static_cast<int>(cinfo.image_width);
fullHeight = static_cast<int>(cinfo.image_height);
cinfo.scale_num = 1;
cinfo.scale_denom = static_cast<unsigned int>(denominator);
cinfo.out_color_space = JCS_RGB;
jpeg_start_decompress(&cinfo);
Image image;
image.width = static_cast<int>(cinfo.output_width);
image.height = static_cast<int>(cinfo.output_height);
image.rgb.resize(static_cast<size_t>(image.width) * image.height * 3);
while (cinfo.output_scanline < cinfo.output_height) {
JSAMPROW row = &image.rgb[static_cast<size_t>(cinfo.output_scanline) * image.width * 3];
jpeg_read_scanlines(&cinfo, &row, 1);
}
jpeg_finish_decompress(&cinfo);
return image;
}
 
int quality(int argc, char** argv, int at) {
const int value = argc > at ? std::atoi(argv[at]) : 85;
if (value < 1 || value > 100) throw std::runtime_error("quality must be between 1 and 100");
return value;
}
 
} // namespace
 
int main(int argc, char** argv) {
const bool encode = argc >= 4 && std::strcmp(argv[1], "encode") == 0;
const bool thumbnail = argc >= 5 && std::strcmp(argv[1], "thumbnail") == 0;
if (!encode && !thumbnail) {
std::fprintf(stderr, "usage: jpeg-tool encode <input.ppm> <output.jpg> [quality]\n jpeg-tool thumbnail <input.jpg> <output.jpg> <1|2|4|8> [quality]\n");
return 2;
}
const int version = LIBJPEG_TURBO_VERSION_NUMBER;
const std::string library = "libjpeg-turbo " + std::to_string(version / 1000000) + "." + std::to_string(version / 1000 % 1000) + "." + std::to_string(version % 1000);
try {
if (encode) {
const int q = quality(argc, argv, 4);
const Image image = readPpm(argv[2]);
const long bytes = writeJpeg(image, argv[3], q);
std::printf("%s encode: %s (%dx%d) -> %s, %ld B at quality %d\n", library.c_str(), argv[2], image.width, image.height, argv[3], bytes, q);
} else {
const int denominator = std::atoi(argv[4]);
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) throw std::runtime_error("the scale must be 1, 2, 4 or 8");
const int q = quality(argc, argv, 5);
int fullWidth = 0, fullHeight = 0;
const Image image = readJpeg(argv[2], denominator, fullWidth, fullHeight);
const long bytes = writeJpeg(image, argv[3], q);
std::printf("%s thumbnail: %s (%dx%d) -> %s (%dx%d), %ld B at quality %d\n", library.c_str(), argv[2], fullWidth, fullHeight, argv[3], image.width, image.height, bytes, q);
}
} catch (const std::exception& error) {
std::fprintf(stderr, "jpeg-tool: %s\n", error.what());
return 1;
}
return 0;
}
shell
npx crossbind build -p wasi -e wasi -b release
wasmtime run --dir=. .crossbind/build/jpeg-tool-wasi-wasm32-st-release.wasm encode photo.ppm photo.jpg 85
wasmtime run --dir=. .crossbind/build/jpeg-tool-wasi-wasm32-st-release.wasm thumbnail photo.jpg thumb.jpg 8 85
output
libjpeg-turbo 3.2.1 encode: photo.ppm (640x480) -> photo.jpg, 15356 B at quality 85
libjpeg-turbo 3.2.1 thumbnail: photo.jpg (640x480) -> thumb.jpg (80x60), 1341 B at quality 85
输入关键词,搜索指南的所有页面和章节。
↑↓ 选择↵ 打开esc 关闭