WebP API文档
本节介绍WebP库中包含的编码器和解码器的API。这个API描述属于版本0.6.1。
头文件和目录
当您安装 libwebp
,一个新的目录webp/
将用平台的典型位置进行安装。例如,在Unix平台上,以下头文件将被复制到/usr/local/include/webp/
。
decode.hencode.htypes.h
这些库位于通常的库目录中。静态和动态库在/usr/local/lib/
Unix平台上。
简单的解码API
要开始使用解码API,您必须确保您已经安装了库和头文件, 如上所述。
在C / C ++代码中包含解码API头文件,如下所示:
#include "webp/decode.h"
int WebPGetInfo(const uint8_t* data, size_t data_size, int* width, int* height);
此功能将验证WebP图像标题并检索图像的宽度和高度。指针*width
和*height
可以传递NULL
如果认为无关紧要。
输入属性
数据
指向WebP图像数据的指针
DATA_SIZE
这是通过data
包含图像数据指向的内存块的大小。
返回
假
在(a)格式化错误的情况下返回错误代码。
真正
成功。*width
并且*height
仅在成功返回有效。
宽度
整数值。范围从1到16383。
高度
整数值。范围从1到16383。
struct WebPBitstreamFeatures { int width; // Width in pixels. int height; // Height in pixels. int has_alpha; // True if the bitstream contains an alpha channel.}VP8StatusCode WebPGetFeatures(const uint8_t* data, size_t data_size, WebPBitstreamFeatures* features);
该功能将从比特流中检索特征。该*features
结构充满了从比特流中收集的信息:
输入属性
数据
指向WebP图像数据的指针
DATA_SIZE
这是通过data
包含图像数据指向的内存块的大小。
返回
VP8_STATUS_OK
当功能成功检索。
VP8_STATUS_NOT_ENOUGH_DATA
当需要更多的数据来从头文件检索功能。
VP8StatusCode
其他情况下的其他错误值。
特征
指向WebPBitstreamFeatures结构的指针。
uint8_t* WebPDecodeRGBA(const uint8_t* data, size_t data_size, int* width, int* height);uint8_t* WebPDecodeARGB(const uint8_t* data, size_t data_size, int* width, int* height);uint8_t* WebPDecodeBGRA(const uint8_t* data, size_t data_size, int* width, int* height);uint8_t* WebPDecodeRGB(const uint8_t* data, size_t data_size, int* width, int* height);uint8_t* WebPDecodeBGR(const uint8_t* data, size_t data_size, int* width, int* height);
这些函数解码指向的WebP图像data
。
WebPDecodeRGBA
按[r0, g0, b0, a0, r1, g1, b1, a1, ...]
顺序返回RGBA图像样本。WebPDecodeARGB
按[a0, r0, g0, b0, a1, r1, g1, b1, ...]
顺序返回ARGB图像样本。WebPDecodeBGRA
按[b0, g0, r0, a0, b1, g1, r1, a1, ...]
顺序返回BGRA图像样本。WebPDecodeRGB
按[r0, g0, b0, r1, g1, b1, ...]
顺序返回RGB图像样本。WebPDecodeBGR
按[b0, g0, r0, b1, g1, r1, ...]
顺序返回BGR图像样本。
调用这些函数的代码必须删除(uint8_t*)
这些函数返回的数据缓冲区 WebPFree()
。
输入属性
数据
指向WebP图像数据的指针
DATA_SIZE
这是通过data
包含图像数据指向的内存块的大小
宽度
整数值。目前范围从1到16383有限。
高度
整数值。目前范围从1到16383有限。
返回
uint8_t *
指向分别以线性RGBA / ARGB / BGRA / RGB / BGR顺序解码的WebP图像样本。
uint8_t* WebPDecodeRGBAInto(const uint8_t* data, size_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride);uint8_t* WebPDecodeARGBInto(const uint8_t* data, size_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride);uint8_t* WebPDecodeBGRAInto(const uint8_t* data, size_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride);uint8_t* WebPDecodeRGBInto(const uint8_t* data, size_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride);uint8_t* WebPDecodeBGRInto(const uint8_t* data, size_t data_size, uint8_t* output_buffer, int output_buffer_size, int output_stride);
这些功能是上述功能的变种,并将图像直接解码成预先分配的缓冲区output_buffer
。在这个缓冲器中可用的最大存储由所指示output_buffer_size
。如果此存储空间不足(或发生错误),NULL
则返回。否则, output_buffer
返回,方便。
该参数output_stride
指定扫描线之间的距离(以字节为单位)。因此,output_buffer_size
预计至少是output_stride * picture - height
。
输入属性
数据
指向WebP图像数据的指针
DATA_SIZE
这是通过data
包含图像数据指向的内存块的大小
output_buffer_size
整数值。分配的缓冲区的大小
output_stride
整数值。指定扫描线之间的距离。
返回
output_buffer
指向解码的WebP图像的指针。
uint8_t *
output_buffer
如果函数成功; NULL
除此以外。
高级解码API
WebP解码支持先进的API,以提供实时裁剪和重新缩放功能,这对于手机等内存受限的环境非常有用。基本上,内存使用量会随着输出的大小而变化,而不是输入的时候,只需要一个快速预览或者放大一部分,否则太大的图片。顺便说一下一些CPU也可以保存。
WebP解码有两种变体,即全图像解码和小输入缓冲区的增量解码。用户可以选择提供一个外部存储缓冲区来解码图像。以下代码示例将介绍使用高级解码API的步骤。
首先我们需要初始化一个配置对象:
#include "webp/decode.h"
WebPDecoderConfig config;CHECK(WebPInitDecoderConfig(&config));
// One can adjust some additional decoding options:config.options.no_fancy_upsampling = 1;config.options.use_scaling = 1;config.options.scaled_width = scaledWidth();config.options.scaled_height = scaledHeight();
// etc.
解码选项收集在WebPDecoderConfig
结构中:
struct WebPDecoderOptions { int bypass_filtering; // if true, skip the in-loop filtering int no_fancy_upsampling; // if true, use faster pointwise upsampler int use_cropping; // if true, cropping is applied <i>first</i> int crop_left, crop_top; // top-left position for cropping. // Will be snapped to even values. int crop_width, crop_height; // dimension of the cropping area int use_scaling; // if true, scaling is applied <i>afterward</i> int scaled_width, scaled_height; // final resolution int use_threads; // if true, use multi-threaded decoding};
可选地,比特流功能可以被读入config.input
,以防我们需要事先知道它们。例如,它可以方便地知道图片是否具有一定的透明度。请注意,这也将解析比特流的头部,因此是比特流看起来像是一个有效的WebP的好方法。
CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
然后我们需要设置解码存储缓冲区,以防止直接提供解码器,而不是依靠解码器进行分配。我们只需要提供指向内存的指针以及缓冲区的总大小和行跨度(scanlines之间的字节距离)。
// Specify the desired output colorspace:config.output.colorspace = MODE_BGRA;// Have config.output point to an external buffer:config.output.u.RGBA.rgba = (uint8_t*)memory_buffer;config.output.u.RGBA.stride = scanline_stride;config.output.u.RGBA.size = total_size_of_the_memory_buffer;config.output.is_external_memory = 1;
图像准备好被解码。有两种可能的解码图像的变种。我们可以使用以下代码一次性解码图像:
CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
或者,我们可以使用增量方法逐渐解码图像作为新的字节可用:
WebPIDecoder* idec = WebPINewDecoder(&config.output);CHECK(idec != NULL);while (additional_data_is_available) { // ... (get additional data in some new_data[] buffer) = WebPIAppend(idec, new_data, new_data_size); if (status != VP8_STATUS_OK && status != VP8_STATUS_SUSPENDED) { break; } // The above call decodes the current available buffer. // Part of the image can now be refreshed by calling // WebPIDecGetRGB()/WebPIDecGetYUVA() etc.}WebPIDelete(idec); // the object doesn't own the image memory, so it can // now be deleted. config.output memory is preserved.
解码图像现在在config.output中(或者,在这种情况下,在config.output.u.RGBA中,因为请求的输出颜色空间是MODE_BGRA)。图像可以保存,显示或以其他方式处理。之后,我们只需要回收配置对象中分配的内存。即使内存是外部的,并且没有被WebPDecode()分配,调用这个函数也是安全的:
WebPFreeDecBuffer(&config.output);
使用这个API,图像也可以被解码为YUV和YUVA格式,分别使用 MODE_YUV
和MODE_YUVA
。这种格式也被称为 Y'CbCr。
简单的编码API
提供了一些非常简单的功能,用于在最常见的布局中编码RGBA样本数组。它们在webp/encode.h
标题中声明为:
size_t WebPEncodeRGB(const uint8_t* rgb, int width, int height, int stride, float quality_factor, uint8_t** output);size_t WebPEncodeBGR(const uint8_t* bgr, int width, int height, int stride, float quality_factor, uint8_t** output);size_t WebPEncodeRGBA(const uint8_t* rgba, int width, int height, int stride, float quality_factor, uint8_t** output);size_t WebPEncodeBGRA(const uint8_t* bgra, int width, int height, int stride, float quality_factor, uint8_t** output);
质量因子quality_factor
范围从0到100,并控制压缩过程中的损耗和质量。值0对应于低质量和小输出尺寸,而100是最高质量和最大输出尺寸。成功时,压缩的字节被放置在*output
指针中,返回大小(以字节为单位),否则返回0,以防失败。调用者必须调用WebPFree()
的*output
指针回收内存。
输入数组应该是一个打包的字节数组(每个通道一个,如函数名称所期望的那样)。stride
对应于从一行跳转到下一行所需的字节数。例如,BGRA布局是:
有无损编码的等价函数,具有签名:
size_t WebPEncodeLosslessRGB(const uint8_t* rgb, int width, int height, int stride, uint8_t** output);size_t WebPEncodeLosslessBGR(const uint8_t* bgr, int width, int height, int stride, uint8_t** output);size_t WebPEncodeLosslessRGBA(const uint8_t* rgba, int width, int height, int stride, uint8_t** output);size_t WebPEncodeLosslessBGRA(const uint8_t* bgra, int width, int height, int stride, uint8_t** output);
高级编码API
在编码器下,编码器带有许多高级编码参数。它们可以更好地平衡压缩效率和处理时间之间的平衡。这些参数收集在WebPConfig
结构中。这种结构最常用的领域是:
struct WebPConfig { int lossless; // Lossless encoding (0=lossy(default), 1=lossless). float quality; // between 0 and 100. For lossy, 0 gives the smallest // size and 100 the largest. For lossless, this // parameter is the amount of effort put into the // compression: 0 is the fastest but gives larger // files compared to the slowest, but best, 100. int method; // quality/speed trade-off (0=fast, 6=slower-better) WebPImageHint image_hint; // Hint for image type (lossless only for now). // Parameters related to lossy compression only: int target_size; // if non-zero, set the desired target size in bytes. // Takes precedence over the 'compression' parameter. float target_PSNR; // if non-zero, specifies the minimal distortion to // try to achieve. Takes precedence over target_size. int segments; // maximum number of segments to use, in [1..4] int sns_strength; // Spatial Noise Shaping. 0=off, 100=maximum. int filter_strength; // range: [0 = off .. 100 = strongest] int filter_sharpness; // range: [0 = off .. 7 = least sharp] int filter_type; // filtering type: 0 = simple, 1 = strong (only used // if filter_strength > 0 or autofilter > 0) int autofilter; // Auto adjust filter's strength [0 = off, 1 = on] int alpha_compression; // Algorithm for encoding the alpha plane (0 = none, // 1 = compressed with WebP lossless). Default is 1. int alpha_filtering; // Predictive filtering method for alpha plane. // 0: none, 1: fast, 2: best. Default if 1. int alpha_quality; // Between 0 (smallest size) and 100 (lossless). // Default is 100. int pass; // number of entropy-analysis passes (in [1..10]). int show_compressed; // if true, export the compressed picture back. // In-loop filtering is not applied. int preprocessing; // preprocessing filter (0=none, 1=segment-smooth) int partitions; // log2(number of token partitions) in [0..3] // Default is set to 0 for easier progressive decoding. int partition_limit; // quality degradation allowed to fit the 512k limit on // prediction modes coding (0: no degradation, // 100: maximum possible degradation). int use_sharp_yuv; // if needed, use sharp (and slow) RGB->YUV conversion};
请注意,大多数这些参数都可以使用cwebp
命令行工具进行实验。
输入样本应该被包装成一个WebPPicture
结构。这个结构可以存储RGBA或YUVA格式的输入样本,具体取决于use_argb
标志的值。
结构组织如下:
struct WebPPicture { int use_argb; // To select between ARGB and YUVA input. // YUV input, recommended for lossy compression. // Used if use_argb = 0. WebPEncCSP colorspace; // colorspace: should be YUVA420 or YUV420 for now (=Y'CbCr). int width, height; // dimensions (less or equal to WEBP_MAX_DIMENSION) uint8_t *y, *u, *v; // pointers to luma/chroma planes. int y_stride, uv_stride; // luma/chroma strides. uint8_t* a; // pointer to the alpha plane int a_stride; // stride of the alpha plane // Alternate ARGB input, recommended for lossless compression. // Used if use_argb = 1. uint32_t* argb; // Pointer to argb (32 bit) plane. int argb_stride; // This is stride in pixels units, not bytes. // Byte-emission hook, to store compressed bytes as they are ready. WebPWriterFunction writer; // can be NULL void* custom_ptr; // can be used by the writer. // Error code for the latest error encountered during encoding WebPEncodingError error_code;
};
这个结构也有一个功能来发送压缩字节,因为它们是可用的。请参阅下面的内存作者示例。其他作家可以直接将数据存储到一个文件(参见 examples/cwebp.c
这个例子)。
使用高级API进行编码的一般流程如下所示:
首先,我们需要建立一个包含压缩参数的编码配置。请注意,相同的配置可用于之后压缩多个不同的图像。
#include "webp/encode.h"WebPConfig config;if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality_factor)) return 0; // version error// Add additional tuning:config.sns_strength = 90;config.filter_sharpness = 6;config.alpha_quality = 90;config_error = WebPValidateConfig(&config); // will verify parameter ranges (always a good habit)
然后,输入样本需要WebPPicture
通过引用或复制引用。这是一个分配缓冲区举例的例子。但是人们可以很容易地设置一个已经分配的样本数组的“视图”。看WebPPictureView()
功能。
// Setup the input data, allocating a picture of width x height dimension
WebPPicture pic;
if (!WebPPictureInit(&pic)) return 0; // version errorpic.width = width;pic.height = height;
if (!WebPPictureAllocate(&pic)) return 0; // memory error
// At this point, 'pic' has been initialized as a container, and can receive the YUVA or RGBA samples.
// Alternatively, one could use ready-made import functions like WebPPictureImportRGBA(), which will take
// care of memory allocation. In any case, past this point, one will have to call WebPPictureFree(&pic)
// to reclaim allocated memory.
为了发送压缩的字节,每次有新字节可用时都调用一个钩子。下面是内存写入器声明的一个简单例子 webp/encode.h
。这个初始化可能需要每张图片进行压缩:
// Set up a byte-writing method (write-to-memory, in this case):WebPMemoryWriter writer;WebPMemoryWriterInit(&writer);pic.writer = WebPMemoryWrite;pic.custom_ptr = &writer;
我们现在准备好压缩输入样本(然后释放它们的内存):
int ok = WebPEncode(&config, &pic);
WebPPictureFree(&pic); // Always free the memory associated with the input.
if (!ok) { printf("Encoding error: %d\n", pic.error_code);
} else { printf("Output size: %d\n", writer.size);
}
为了更高级地使用API和结构,建议查看webp/encode.h
标题中提供的文档。阅读示例代码examples/cwebp.c
可以证明对于发现使用较少的参数很有用。