
Android 10(r33)의 WebP 코덱 라이브러리를 대상으로 하는 CVE-2023-1999용 개념 증명 익스플로잇. libwebp 라이브러리의 힙 버퍼 오버플로우 취약점을 시연하여 조작된 WebP 이미지를 통한 원격 코드 실행을 가능하게 합니다.
/ \\/ \/ _ \/ _ )/ _ \
\ / __/ _ \ __/
\__\__/\____/\_____/__/ ____ ___
/ _/ / \ \ / _ \/ _/
/ \_/ / / \ \ __/ \__
\____/____/\_____/_____/____/v1.0.2
WebP 코덱: WebP 형식의 이미지를 인코딩하고 디코딩하는 라이브러리입니다. 이 패키지에는 다른 프로그램에서 WebP 지원을 추가하는 데 사용할 수 있는 라이브러리와 명령줄 도구 'cwebp' 및 'dwebp'가 포함되어 있습니다.
http://developers.google.com/speed/webp 참조
최신 소스 트리는 다음에서 확인할 수 있습니다. https://chromium.googlesource.com/webm/libwebp
WebM 프로젝트와 동일한 라이선스로 배포됩니다. 자세한 내용은 http://www.webmproject.org/license/software/ 또는 "COPYING" 파일을 참조하세요. 추가 지적 재산권 부여는 PATENTS 파일에서 확인할 수 있습니다.
다음을 실행하여:
nmake /f Makefile.vc CFG=release-static RTLIBCFG=static OBJDIR=output
output\release-static(x64|x86)\bin 디렉터리에는 cwebp.exe 및 dwebp.exe 도구가 들어 있습니다. output\release-static(x64|x86)\lib 디렉터리에는 libwebp 정적 라이브러리가 들어 있습니다. 대상 아키텍처(x86/x64)는 시스템 경로에 있는 Visual Studio 컴파일러(cl.exe)를 통해 Makefile.vc가 감지합니다.
GNU 도구(gcc 및 make)가 설치된 플랫폼에서 다음을 실행하면
make -f makefile.unix
examples/cwebp 및 examples/dwebp 바이너리와 정적 라이브러리 src/libwebp.a를 빌드합니다. autoconf 도구 기반의 전체 설치 시스템에 대한 간단한 대안이므로 시스템 전체 설치를 제공하지는 않습니다(아래 참조). 추가 세부 사항 및 사용자 지정은 makefile.unix를 참조하세요.
사전 요구 사항: 컴파일러(예: gcc), make, autoconf, automake, libtool. Debian 계열 시스템에서는 다음 명령으로 최소 빌드에 필요한 모든 것을 설치할 수 있습니다: $ sudo apt-get install gcc make autoconf automake libtool
git 소스에서 빌드할 때는 configure 스크립트를 생성하기 위해 autogen.sh를 실행해야 합니다.
./configure make make install
다음 파일을 얻으려면 위 명령만 실행하면 됩니다.
/usr/local/include/webp/decode.h /usr/local/include/webp/encode.h /usr/local/include/webp/types.h /usr/local/lib/libwebp.* /usr/local/bin/cwebp /usr/local/bin/dwebp
설치됩니다.
참고: '--enable-libwebpdecoder' 플래그를 사용하여 디코딩 전용 라이브러리인 libwebpdecoder를 이용할 수 있습니다. 인코딩 라이브러리는 별도로 빌드되며 해당 Makefile.am configure 파일을 약간 수정하면 독립적으로 설치할 수 있습니다(해당 파일의 주석 참조). 더 많은 옵션은 './configure --help'를 참조하세요.
안정적인 MIPS Linux 툴체인 릴리스는 다음에서 확인할 수 있습니다: https://community.imgtec.com/developers/mips/tools/codescape-mips-sdk/available-releases/
export PATH=$PATH:/path/to/toolchain/bin
HOST=mips-mti-linux-gnu
MIPS_CFLAGS="-O3 -mips32r5 -mabi=32 -mtune=p5600 -mmsa -mfp64
-msched-weight -mload-store-pairs -fPIE"
MIPS_LDFLAGS="-mips32r5 -mabi=32 -mmsa -mfp64 -pie"
HOST=mips-img-linux-gnu
MIPS_CFLAGS="-O3 -mips64r6 -mabi=64 -mtune=i6400 -mmsa -mfp64
-msched-weight -mload-store-pairs -fPIE"
MIPS_LDFLAGS="-mips64r6 -mabi=64 -mmsa -mfp64 -pie"
./configure --host=${HOST} --build=config.guess
CC="${HOST}-gcc -EL"
CFLAGS="$MIPS_CFLAGS"
LDFLAGS="$MIPS_LDFLAGS"
make
make install
CMake를 사용하면 libwebp, cwebp, dwebp, gif2web, img2webp, webpinfo 및 JS 바인딩을 컴파일할 수 있습니다.
사전 요구 사항: 컴파일러(예: autotools와 함께 제공되는 gcc) 및 CMake. Debian 계열 시스템에서는 다음 명령으로 최소 빌드에 필요한 모든 것을 설치할 수 있습니다: $ sudo apt-get install build-essential cmake
git 소스에서 빌드할 때는 makefile을 생성하기 위해 cmake를 실행해야 합니다.
mkdir build && cd build && cmake ../ make make install
실행 파일도 필요하다면 CMake를 통해 활성화해야 합니다. 예:
cmake -DWEBP_BUILD_CWEBP=ON -DWEBP_BUILD_DWEBP=ON ../
또는 선호하는 인터페이스(ccmake 또는 cmake-qt-gui)를 통해 활성화할 수 있습니다.
Windows에서 유니코드를 지원하려면 -DWEBP_UNICODE=ON 옵션을 사용하세요(chcp 65001 포함).
마지막으로 설치가 완료되면 다음을 수행하여 CMake 프로젝트에서 WebP를 사용할 수도 있습니다:
find_package(WebP)
그러면 CMake 변수 WebP_INCLUDE_DIRS 및 WebP_LIBRARIES가 정의됩니다.
Gradle 지원은 최소한입니다. libwebp, cwebp, dwebp 및 webpmux_example를 컴파일하는 데만 도움이 됩니다.
사전 요구 사항: 컴파일러(예: autotools와 함께 제공되는 gcc) 및 gradle. Debian 계열 시스템에서는 다음 명령으로 최소 빌드에 필요한 모든 것을 설치할 수 있습니다: $ sudo apt-get install build-essential gradle
git 소스에서 빌드할 때는 적절한 타겟으로 Gradle 래퍼를 실행해야 합니다. 예:
./gradlew buildAllExecutables
swig/libwebp.swig에서 언어 바인딩을 생성하려면 최소 swig-1.3(http://www.swig.org)이 필요합니다.
현재 다음 함수가 매핑되어 있습니다: Decode: WebPGetDecoderVersion WebPGetInfo WebPDecodeRGBA WebPDecodeARGB WebPDecodeBGRA WebPDecodeBGR WebPDecodeRGB
Encode: WebPGetEncoderVersion WebPEncodeRGBA WebPEncodeBGRA WebPEncodeRGB WebPEncodeBGR WebPEncodeLosslessRGBA WebPEncodeLosslessBGRA WebPEncodeLosslessRGB WebPEncodeLosslessBGR
자세한 빌드 지침은 swig/README를 참조하세요.
Java 바인딩:
swig로 생성된 JNI 래퍼 코드를 빌드하려면 enum 지원을 위해 최소 JDK-1.5(또는 이에 상응하는 버전)가 필요합니다. 출력 결과는 System.loadLibrary("webp_jni")를 통해 로드할 수 있는 공유 객체/DLL로 제공됩니다.
Python 바인딩:
swig로 생성된 Python 확장 코드를 빌드하려면 최소 Python 2.6이 필요합니다. Python < 2.6은 libwebp.swig 또는 생성된 코드를 약간 수정하면 빌드될 수 있지만 테스트되지 않았습니다.
examples/ 디렉터리에는 이미지 인코딩(cwebp) 및 디코딩(dwebp) 도구가 포함되어 있습니다.
가장 간단한 사용법은 다음과 같습니다: cwebp input.png -q 80 -o output.webp 이 명령은 0->100 척도(0은 최저 품질, 100은 최고 품질. 기본값은 75)에서 품질 계수 80을 사용하여 입력 파일을 WebP 파일로 변환합니다. -lossless 플래그도 사용해 볼 수 있습니다. 이 플래그는 소스(RGBA 형식)를 손실 없이 압축합니다. 이 경우 -q 품질 매개변수는 출력 파일을 가능한 한 작게 만드는 데 소요되는 처리 시간을 제어합니다.
-longhelp 명령줄 플래그를 사용하면 더 긴 옵션 목록을 볼 수 있습니다:
cwebp -longhelp Usage: cwebp [-preset <...>] [options] in_file [-o out_file]
If input size (-s) for an image is not specified, it is assumed to be a PNG, JPEG, TIFF or WebP file.
Options: -h / -help ............. short help -H / -longhelp ......... long help -q ............. quality factor (0:small..100:big), default=75 -alpha_q ......... transparency-compression quality (0..100), default=100 -preset ....... preset setting, one of: default, photo, picture, drawing, icon, text -preset must come first, as it overwrites other parameters -z ............... activates lossless preset with given level in [0:fast, ..., 9:slowest]
-m ............... compression method (0=fast, 6=slowest), default=4 -segments ........ number of segments to use (1..4), default=4 -size ............ target size (in bytes) -psnr .......... target PSNR (in dB. typically: 42)
-s ......... input size (width x height) for YUV -sns ............. spatial noise shaping (0:off, 100:max), default=50 -f ............... filter strength (0=off..100), default=60 -sharpness ....... filter sharpness (0:most .. 7:least sharp), default=0 -strong ................ use strong filter instead of simple (default) -nostrong .............. use simple filter instead of strong -sharp_yuv ............. use sharper (and slower) RGB->YUV conversion -partition_limit . limit quality to fit the 512k limit on the first partition (0=no degradation ... 100=full) -pass ............ analysis pass number (1..10) -crop .. crop picture with the given rectangle -resize ........ resize picture (after any cropping) -mt .................... use multi-threading if available -low_memory ............ reduce memory usage (slower encoding) -map ............. print map of extra info -print_psnr ............ prints averaged PSNR distortion -print_ssim ............ prints averaged SSIM distortion -print_lsim ............ prints local-similarity distortion -d <file.pgm> .......... dump the compressed output (PGM file) -alpha_method .... transparency-compression method (0..1), default=1 -alpha_filter . predictive filtering for alpha plane, one of: none, fast (default) or best -exact ................. preserve RGB values in transparent area, default=off -blend_alpha ..... blend colors against background color expressed as RGB values written in hexadecimal, e.g. 0xc0e0d0 for red=0xc0 green=0xe0 and blue=0xd0 -noalpha ............... discard any transparency information -lossless .............. encode image losslessly, default=off -near_lossless ... use near-lossless image preprocessing (0..100=off), default=100 -hint ......... specify image characteristics hint, one of: photo, picture or graph
-metadata ..... comma separated list of metadata to copy from the input to the output if present. Valid values: all, none (default), exif, icc, xmp
-short ................. condense printed message -quiet ................. don't print anything -version ............... print version number and exit -noasm ................. disable all assembly optimizations -v ..................... verbose, e.g. print encoding/decoding times -progress .............. report encoding progress
Experimental Options: -jpeg_like ............. roughly match expected JPEG size -af .................... auto-adjust filter strength -pre ............. pre-processing filter
시각적 품질을 추가로 조정하기 위해 시도해 볼 만한 주요 옵션은 다음과 같습니다: -preset -sns -f -m
즉:
examples/dwebp.c에는 .webp 파일을 가져와 PNG 이미지 파일(및 기타 형식)로 디코딩하는 디코딩 샘플이 있습니다. 이는 단순히 API 사용을 보여주기 위한 것입니다. 다음 명령을 사용하여 test.webp 파일이 test_ref.ppm과 정확히 동일하게 디코딩되는지 확인할 수 있습니다:
cd examples ./dwebp test.webp -ppm -o test.ppm diff test.ppm test_ref.ppm
전체 옵션 목록은 -h를 사용하여 확인할 수 있습니다:
dwebp -h Usage: dwebp in_file [options] [-o out_file]
Decodes the WebP image file to PNG format [Default] Use following options to convert into alternate image formats: -pam ......... save the raw RGBA samples as a color PAM -ppm ......... save the raw RGB samples as a color PPM -bmp ......... save as uncompressed BMP format -tiff ........ save as uncompressed TIFF format -pgm ......... save the raw YUV samples as a grayscale PGM file with IMC4 layout -yuv ......... save the raw YUV samples in flat layout
Other options are: -version ..... print version number and exit -nofancy ..... don't use the fancy YUV420 upscaler -nofilter .... disable in-loop filtering -nodither .... disable dithering -dither .. dithering strength (in 0..100) -alpha_dither use alpha-plane dithering if needed -mt .......... use multi-threading -crop ... crop output with the given rectangle -resize ......... scale the output (after any cropping) -flip ........ flip the output vertically -alpha ....... only save the alpha plane -incremental . use incremental decoding (useful for tests) -h ........... this help message -v ........... verbose (e.g. print encoding/decoding times) -quiet ....... quiet mode, don't print anything -noasm ....... disable all assembly optimizations
'webpinfo'는 WebP 파일의 청크 수준 구조와 비트스트림 헤더 정보를 출력하는 데 사용할 수 있습니다. 또한 파일이 유효한 WebP 형식인지 확인할 수도 있습니다.
Usage: webpinfo [options] in_files Note: there could be multiple input files; options must come before input files. Options: -version ........... Print version number and exit. -quiet ............. Do not show chunk parsing information. -diag .............. Show parsing error diagnosis. -summary ........... Show chunk stats summary. -bitstream_info .... Parse bitstream header.
examples/ 디렉터리 아래에 'vwebp'라는 간단한 셀프서비스 시각화 도구가 있습니다. OpenGL을 사용하여 간단한 그리기 창을 열고 디코딩된 WebP 파일을 표시합니다. 아직 automake 빌드 시스템에 통합되지 않았지만 아래 권장 사항을 사용하여 수동으로 컴파일해 볼 수 있습니다.
Usage: vwebp in_file [options]
Decodes the WebP image file and visualize it using OpenGL Options are: -version ..... print version number and exit -noicc ....... don't use the icc profile if present -nofancy ..... don't use the fancy YUV420 upscaler -nofilter .... disable in-loop filtering -dither dithering strength (0..100), default=50 -noalphadither disable alpha plane dithering -usebgcolor .. display background color -mt .......... use multi-threading -info ........ print info -h ........... this help message
Keyboard shortcuts: 'c' ................ toggle use of color profile 'b' ................ toggle background color display 'i' ................ overlay file information 'd' ................ disable blending & disposal (debug) 'q' / 'Q' / ESC .... quit
사전 요구 사항:
OpenGL 및 OpenGL 유틸리티 툴킷(GLUT) Linux: $ sudo apt-get install freeglut3-dev mesa-common-dev Mac + XCode:
(선택 사항) qcms (Quick Color Management System) i. Mozilla / Chromium에서 qcms 다운로드: http://hg.mozilla.org/mozilla-central/file/0e7639e3bdfb/gfx/qcms http://src.chromium.org/viewvc/chrome/trunk/src/third_party/qcms ii. 소스 파일을 libqcms.a / qcms.lib으로 빌드하고 아카이브합니다. iii. makefile.unix / Makefile.vc 업데이트 a) WEBP_HAVE_QCMS 정의 b) qcms 디렉터리를 참조하도록 include / library 경로 업데이트
makefile.unix / Makefile.vc를 사용하여 빌드: $ make -f makefile.unix examples/vwebp
nmake /f Makefile.vc CFG=release-static
../obj/x64/release-static/bin/vwebp.exe
'img2webp' 유틸리티는 일련의 입력 이미지(PNG, JPEG, ...)를 애니메이션 WebP 파일로 변환할 수 있습니다. 지속 시간, 인코딩 모드 등을 세밀하게 제어할 수 있습니다.
Usage:
img2webp [file-level options] [image files...] [per-frame options...]
File-level options (only used at the start of compression): -min_size ............ minimize size -loop .......... loop count (default: 0, = infinite loop) -kmax .......... maximum number of frame between key-frames (0=only keyframes) -kmin .......... minimum number of frame between key-frames (0=disable key-frames altogether) -mixed ............... use mixed lossy/lossless automatic mode -v ................... verbose mode -h ................... this help -version ............. print version number and exit
Per-frame options (only used for subsequent images input): -d ............. frame duration in ms (default: 100) -lossless ........... use lossless mode (default) -lossy ... ........... use lossy mode -q ........... quality -m ............. method to use
example: img2webp -loop 2 in0.png -lossy in1.jpg -d 80 in2.tiff -o out.webp
참고: 단일 파일 이름이 인수로 전달되면 인수는 이 파일에서 토큰화됩니다. 파일 이름은 '-' 문자로 시작하면 안 됩니다.
examples/ 아래에 있는 gif2webp 유틸리티를 사용하여 애니메이션 GIF 파일을 애니메이션 WebP 파일로 변환할 수 있습니다. 그런 다음 vwebp를 사용하여 파일을 볼 수 있습니다.
Usage: gif2webp [options] gif_file -o webp_file Options: -h / -help ............. this help -lossy ................. encode image using lossy compression -mixed ................. for each frame in the image, pick lossy or lossless compression heuristically -q ............. quality factor (0:small..100:big) -m ............... compression method (0=fast, 6=slowest) -min_size .............. minimize output size (default:off) lossless compression by default; can be combined with -q, -m, -lossy or -mixed options -kmin ............ min distance between key frames -kmax ............ max distance between key frames -f ............... filter strength (0=off..100) -metadata ..... comma separated list of metadata to copy from the input to the output if present Valid values: all, none, icc, xmp (default) -loop_compatibility .... use compatibility mode for Chrome version prior to M62 (inclusive) -mt .................... use multi-threading if available
-version ............... print version number and exit -v ..................... verbose -quiet ................. don't print anything
libgif 개발 파일이 설치되어 있으면 makefile.unix를 사용하여 gif2webp를 빌드할 수 있습니다: $ make -f makefile.unix examples/gif2webp
또는 autoconf를 사용하여: $ ./configure --enable-everything $ make
examples/ 아래의 테스트 유틸리티 anim_diff를 사용하여 두 개의 애니메이션 이미지(각각 GIF 또는 WebP일 수 있음)를 비교할 수 있습니다.사용법: anim_diff [options]
옵션: -dump_frames 디코딩된 프레임을 PAM 형식으로 덤프합니다. -min_psnr ... 프레임별 최소 PSNR -raw_comparison ..... 이 플래그를 사용하지 않으면 비교 전에 RGB가 프리멀티플라이됩니다. -max_diff ..... 후속 프레임의 해당 픽셀 간 채널별 허용 최대 차이 -h .................. 도움말 표시 -version ............ 버전 번호를 출력하고 종료
libgif 개발 파일과 C++ 컴파일러가 설치되어 있으면 anim_diff를 makefile.unix를 사용하여 빌드할 수 있습니다: $ make -f makefile.unix examples/anim_diff
또는 autoconf를 사용하여: $ ./configure --enable-everything $ make
주요 인코딩 함수는 헤더 src/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);
이 함수들은 원시 RGB 샘플을 WebP 데이터로 변환합니다. 제공되는 유일한 제어 항목은 품질 계수(quality factor)입니다.
무손실 형식을 사용하기 위한 변형 함수도 있습니다:
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 및 WebPPicture 구조체를 기반으로 합니다.
WebPConfig는 인코딩 설정을 포함하며 특정 이미지에 종속되지 않습니다. WebPPicture는 입력 데이터를 포함하며, 압축에 일부 WebPConfig가 사용됩니다. 인코딩 흐름은 다음과 같습니다:
-------------------------------------- BEGIN PSEUDO EXAMPLE
#include <webp/encode.h>
// Setup a config, starting form a preset and tuning some additional // parameters WebPConfig config; if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, quality_factor)) return 0; // version error } // ... additional tuning config.sns_strength = 90; config.filter_sharpness = 6; config_error = WebPValidateConfig(&config); // not mandatory, but useful
// Setup the input data WebPPicture pic; if (!WebPPictureInit(&pic)) { return 0; // version error } pic.width = width; pic.height = height; // allocated picture of dimension width x height if (!WebPPictureAllocate(&pic)) { return 0; // memory error } // at this point, 'pic' has been initialized as a container, // and can receive the Y/U/V samples. // Alternatively, one could use ready-made import functions like // WebPPictureImportRGB(), which will take care of memory allocation. // In any case, past this point, one will have to call // WebPPictureFree(&pic) to reclaim memory.
// Set up a byte-output write method. WebPMemoryWriter, for instance. WebPMemoryWriter wrt; WebPMemoryWriterInit(&wrt); // initialize 'wrt'
pic.writer = MyFileWriter; pic.custom_ptr = my_opaque_structure_to_make_MyFileWriter_work;
// Compress! int ok = WebPEncode(&config, &pic); // ok = 0 => error occurred! WebPPictureFree(&pic); // must be called independently of the 'ok' result.
// output data should have been handled by the writer at that point. // -> compressed data is the memory buffer described by wrt.mem / wrt.size
// deallocate the memory used by compressed data WebPMemoryWriterClear(&wrt);
-------------------------------------- END PSEUDO EXAMPLE
주로 다음 함수 하나만 호출하면 됩니다:
#include "webp/decode.h" uint8_t* WebPDecodeRGB(const uint8_t* data, size_t data_size, int* width, int* height);
자세한 내용은 src/webp/decode.h 파일을 참조하십시오. BGR/RGBA/ARGB/BGRA 순서로 디코딩하는 변형과 원시 Y'CbCr 샘플로 디코딩하는 변형이 있습니다. 또한 사전 할당된 버퍼로 이미지를 직접 디코딩할 수도 있습니다.
WebP 파일을 감지하고 이미지의 크기를 얻으려면 다음 함수가 제공됩니다: int WebPGetInfo(const uint8_t* data, size_t data_size, int* width, int* height); 이 함수를 사용할 때는 디코딩이 수행되지 않습니다.
데이터가 점진적으로 전송되는 경우, 약간 더 복잡한 API를 사용하여 이미지를 여전히 증분 디코딩할 수 있습니다. 디코더 상태는 WebPIDecoder 객체 인스턴스에 저장됩니다. 이 객체는 RGB 또는 Y'CbCr 샘플을 디코딩할 목적으로 생성할 수 있습니다. 예를 들어:
WebPDecBuffer buffer; WebPInitDecBuffer(&buffer); buffer.colorspace = MODE_BGR; ... WebPIDecoder* idec = WebPINewDecoder(&buffer);
데이터가 점진적으로 제공됨에 따라 이 증분 디코더 객체를 사용하여 이미지를 계속 디코딩할 수 있습니다. 새로 도착한 데이터를 전달하는 방법에는 상호 배타적인 두 가지가 있습니다:
새 바이트를 추가하는 방법:
WebPIAppend(idec, fresh_data, size_of_fresh_data);
또는 전송된 데이터의 새 크기만 지정하는 방법:
WebPIUpdate(idec, buffer, size_of_transmitted_buffer);
'buffer'는 WebPIUpdate에 대한 각 호출 사이에 수정될 수 있습니다. 특히 더 큰 데이터를 수용하기 위해 버퍼 크기가 조정되는 경우가 그렇습니다.
이 함수들은 디코딩 상태를 반환합니다. 디코딩이 아직 끝나지 않았으면 VP8_STATUS_SUSPENDED, 디코딩이 완료되면 VP8_STATUS_OK입니다. 그 외의 상태는 오류 조건입니다.
'idec' 객체는 (오류 조건에서도) 항상 WebPDelete(idec)를 호출하여 해제해야 합니다.
부분적으로 디코딩된 이미지 샘플을 가져오려면 해당 메서드인 WebPIDecGetRGB 또는 WebPIDecGetYUVA를 사용해야 합니다. 이 메서드는 마지막으로 표시 가능한 픽셀 행을 반환합니다.
마지막으로, 사전 할당된 픽셀 버퍼로 디코딩을 수행할 수도 있습니다. 이 버퍼는 WebPINewRGB() 또는 WebPINewYUVA()를 호출하여 WebPIDecoder를 생성할 때 전달해야 합니다.
자세한 내용은 src/webp/decode.h 헤더를 참조하십시오.
WebP 디코딩은 즉석 크롭(cropping) 및 크기 조정을 제공하는 고급 API를 지원합니다. 이는 모바일 폰과 같이 메모리가 제한된 환경에서 매우 유용합니다. 기본적으로, 원본 이미지가 너무 커서 빠른 미리보기나 확대된 일부 영역만 필요한 경우 메모리 사용량은 입력 크기가 아닌 출력 크기에 비례합니다. 부수적으로 CPU도 절약할 수 있습니다.
-------------------------------------- BEGIN PSEUDO EXAMPLE // A) Init a configuration object WebPDecoderConfig config; CHECK(WebPInitDecoderConfig(&config));
// B) optional: retrieve the bitstream's features.
CHECK(WebPGetFeatures(data, data_size, &config.input) == VP8_STATUS_OK);
// C) Adjust 'config' options, if needed
config.options.no_fancy_upsampling = 1;
config.options.use_scaling = 1;
config.options.scaled_width = scaledWidth();
config.options.scaled_height = scaledHeight();
// etc.
// D) Specify 'config' output options for specifying output colorspace.
// Optionally the external image decode buffer can also be specified.
config.output.colorspace = MODE_BGRA;
// Optionally, the config.output can be pointed to an external buffer as
// well for decoding the image. This externally supplied memory buffer
// should be big enough to store the decoded picture.
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;
// E) Decode the WebP image. There are two variants w.r.t decoding image.
// The first one (E.1) decodes the full image and the second one (E.2) is
// used to incrementally decode the image using small input buffers.
// Any one of these steps can be used to decode the WebP image.
// E.1) Decode full image.
CHECK(WebPDecode(data, data_size, &config) == VP8_STATUS_OK);
// E.2) Decode image incrementally.
WebPIDecoder* const idec = WebPIDecode(NULL, NULL, &config);
CHECK(idec != NULL);
while (bytes_remaining > 0) {
VP8StatusCode status = WebPIAppend(idec, input, bytes_read);
if (status == VP8_STATUS_OK || status == VP8_STATUS_SUSPENDED) {
bytes_remaining -= bytes_read;
} else {
break;
}
}
WebPIDelete(idec);
// F) Decoded image is now in config.output (and config.output.u.RGBA).
// It can be saved, displayed or otherwise processed.
// G) Reclaim memory allocated in config's object. It's safe to call
// this function even if the memory is external and wasn't allocated
// by WebPDecode().
WebPFreeDecBuffer(&config.output);
-------------------------------------- END PSEUDO EXAMPLE
모든 버그는 이슈 트래커에 보고해 주십시오: https://bugs.chromium.org/p/webp 패치는 언제나 환영합니다! 시작하려면 이 페이지를 참조하십시오: http://www.webmproject.org/code/contribute/submitting-patches/