WebP API 說明文件

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

本節說明 WebP 程式庫所含編碼器與解碼器的 API。此 API 說明適用於 1.3.0 版。

標頭和程式庫

安裝 libwebp 時,系統會在平台的一般位置安裝名為 webp/ 的目錄。例如,在 Unix 平台上,系統會將下列標頭檔案複製到 /usr/local/include/webp/

decode.h
encode.h
types.h

程式庫位於一般的程式庫目錄中。靜態和動態程式庫在 Unix 平台上的 /usr/local/lib/ 中。

簡易解碼 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 指向且包含圖片資料的記憶體區塊大小。

傳回

發生 (a) 格式設定錯誤時傳回的錯誤代碼。
true
成功。*width*height 只有在成功傳回時才有效。
width
整數值。範圍是 1 到 16383。
height
整數值。範圍是限制在 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.
  int has_animation;  // True if the bitstream is an animation.
  int format;         // 0 = undefined (/mixed), 1 = lossy, 2 = lossless
}

VP8StatusCode WebPGetFeatures(const uint8_t* data,
                              size_t data_size,
                              WebPBitstreamFeatures* features);

此函式會從位元流擷取功能。*features 結構會填入從位元流收集的資訊:

輸入屬性

資料
連結至 WebP 圖片資料
資料大小
這是由 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);

這些函式會將 data 指向的 WebP 圖片解碼。

  • 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 圖片樣本。

呼叫任何這些函式的程式碼都必須刪除這些函式使用 WebPFree() 傳回的資料緩衝區 (uint8_t*)

輸入屬性

資料
連結至 WebP 圖片資料
資料大小
這是 data 指向含有圖片資料的記憶體區塊大小
width
整數值。目前範圍僅限於 1 到 16383。
height
整數值。目前範圍僅限於 1 到 16383。

傳回

uint8_t*
指向已解碼的 WebP 圖片樣本,分別採用線性 RGBA/ARGB/BGRA/RGB/BGR 順序。
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 指向含有圖片資料的記憶體區塊大小
輸出緩衝區大小
整數值。分配的緩衝區大小
輸出_步階
整數值。指定掃描線之間的距離。

傳回

輸出_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 first 
  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 afterward
  int scaled_width, scaled_height;  // final resolution
  int use_threads;                  // if true, use multi-threaded decoding
  int dithering_strength;           // dithering strength (0=Off, 100=full)
  int flip;                         // if true, flip output vertically
  int alpha_dithering_strength;     // alpha dithering strength in [0..100]
};

您可以選擇將位元流功能讀取為 config.input,以防我們事先瞭解這些功能。例如,瞭解圖片是否完全透明請注意,這樣做也會剖析位元流的標頭,因此您可以瞭解位元流是否看似有效的 WebP 格式。

CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);

接著,我們需要設定解碼記憶體緩衝區,這樣想直接提供緩衝區,而不依賴解碼器的分配。我們只需要提供記憶體的指標,以及緩衝區與行走的總大小 (掃描線之間的距離,以位元組為單位)。

// 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)
  VP8StatusCode status = 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,圖片也可以分別以 MODE_YUVMODE_YUVA 解碼為 YUV 和 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)。呼叫端必須呼叫 *output 指標上的 WebPFree() 以收回記憶體。

輸入陣列應為已封裝的位元組陣列 (每個管道一個,如函式名稱所預期)。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);

請注意,這些函式 (如有損版本) 均使用程式庫的預設設定。如果是無損,表示 [確切] 已停用。系統會修改透明區域中的 RGB 值以改善壓縮。如要避免這種情況發生,請使用 WebPEncode() 並將 WebPConfig::exact 設為 1

進階編碼 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 error
pic.width = width;
pic.height = height;
if (!WebPPictureAlloc(&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 有助於發現使用較少參數的情況。