Skip to content
KitploitKITPLOIT
ИнструментыБлог
Отправить
ИнструментыБлог
Отправить

Инструменты для хакинга, пентеста и кибербезопасности — ваш арсенал защиты!

Kitploit — это каталог инструментов для хакинга, кибербезопасности и пентестинга. Находите последние обновления проектов для поиска уязвимостей, анализа систем, автоматизации тестирования и усиления вашей безопасности.

··Ленты·Контакты·Конфиденциальность·© 2026 Kitploit

Каталог инструментов

Категории

Все категории
Loading categories
webp_Android10_r33_CVE-2023-1999 | Kitploit
Инструменты/GitHubGitHub/pazhanivelmani/webp_android10_r33_cve-2023-1999
Статический анализАнализ уязвимостейАнализ КодаЭксплуатацияФаззингАнализ Бинарных Файлов
GitHubpazhanivelmani/webp_android10_r33_cve-2023-1999

webp_Android10_r33_CVE-2023-1999

Репозиторий

Популярное

Смотреть все →

Откройте для себя самые используемые инструменты нашего сообщества.

Изучить все инструменты

Просмотрите нашу коллекцию инструментов

Смотреть все инструменты →
Поделиться
11 год назадЕщё не проверено

root@kitploit:~
     /  \\/  \/  _ \/  _ )/  _ \
     \       /   __/  _  \   __/
      \__\__/\____/\_____/__/ ____  ___
            / _/ /    \    \ /  _ \/ _/
           /  \_/   / /   \ \   __/  \__
           \____/____/\_____/_____/____/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.

Сборка:

Сборка в Windows:

Выполнив:

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) определяется Makefile.vc из компилятора Visual Studio (cl.exe), доступного в системном пути.

Сборка в Unix с использованием makefile.unix:

На платформах с установленными инструментами GNU (gcc и make), выполнение

make -f makefile.unix

соберёт бинарные файлы examples/cwebp и examples/dwebp, а также статическую библиотеку src/libwebp.a. Общесистемная установка не предусмотрена, так как это простая альтернатива полной системе установки, основанной на инструментах autoconf (см. ниже). Пожалуйста, обратитесь к makefile.unix за дополнительными деталями и настройками.

Использование инструментов autoconf:

Предварительные требования: Компилятор (например, gcc), make, autoconf, automake, libtool. В системе, подобной Debian, следующая команда должна установить всё необходимое для минимальной сборки: $ sudo apt-get install gcc make autoconf automake libtool

При сборке из исходников git вам нужно будет запустить autogen.sh для генерации скрипта configure.

./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

установленными.

Примечание: библиотека только для декодирования, libwebpdecoder, доступна с помощью флага '--enable-libwebpdecoder'. Библиотека кодирования собирается отдельно и может быть установлена независимо с помощью небольшого изменения в соответствующих файлах configure Makefile.am (см. комментарии там). См. './configure --help' для дополнительных опций.

Сборка для MIPS Linux:

Стабильные доступные релизы тулчейна MIPS Linux можно найти по адресу: https://community.imgtec.com/developers/mips/tools/codescape-mips-sdk/available-releases/

Добавить тулчейн в PATH

export PATH=$PATH:/path/to/toolchain/bin

32-битная сборка для mips32r5 (p5600)

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"

64-битная сборка для mips64r6 (i6400)

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:

С помощью CMake вы можете скомпилировать libwebp, cwebp, dwebp, gif2web, img2webp, webpinfo и привязки для JS.

Предварительные требования: Компилятор (например, gcc с autotools) и CMake. В системе, подобной Debian, следующая команда должна установить всё необходимое для минимальной сборки: $ sudo apt-get install build-essential cmake

При сборке из исходников git вам нужно будет запустить cmake для генерации makefile.

mkdir build && cd build && cmake ../ make make install

Если вы также хотите получить какие-либо из исполняемых файлов, вам нужно будет включить их через CMake, например:

cmake -DWEBP_BUILD_CWEBP=ON -DWEBP_BUILD_DWEBP=ON ../

или через ваш любимый интерфейс (например, ccmake или cmake-qt-gui).

Используйте опцию -DWEBP_UNICODE=ON для поддержки Unicode в Windows (с chcp 65001).

Наконец, после установки вы также можете использовать WebP в своём проекте CMake, выполнив:

find_package(WebP)

что определит переменные CMake WebP_INCLUDE_DIRS и WebP_LIBRARIES.

Gradle:

Поддержка Gradle минимальна: она помогает только скомпилировать libwebp, cwebp, dwebp и webpmux_example.

Предварительные требования: Компилятор (например, gcc с autotools) и gradle. В системе, подобной Debian, следующая команда должна установить всё необходимое для минимальной сборки: $ sudo apt-get install build-essential gradle

При сборке из исходников git вам нужно будет запустить обёртку Gradle с соответствующей целью, например:

./gradlew buildAllExecutables

Привязки SWIG:

Для генерации языковых привязок из swig/libwebp.swig требуется как минимум swig-1.3 (http://www.swig.org).

В настоящее время сопоставлены следующие функции: Декодирование: WebPGetDecoderVersion WebPGetInfo WebPDecodeRGBA WebPDecodeARGB WebPDecodeBGRA WebPDecodeBGR WebPDecodeRGB

Кодирование: WebPGetEncoderVersion WebPEncodeRGBA WebPEncodeBGRA WebPEncodeRGB WebPEncodeBGR WebPEncodeLosslessRGBA WebPEncodeLosslessBGRA WebPEncodeLosslessRGB WebPEncodeLosslessBGR

См. swig/README для более подробных инструкций по сборке.

Привязки Java:

Для сборки сгенерированного SWIG кода обёртки JNI необходим как минимум JDK-1.5 (или эквивалент) для поддержки перечислений. Результат предполагается в виде общей библиотеки / DLL, которую можно загрузить через System.loadLibrary("webp_jni").

Привязки Python:

Для сборки сгенерированного SWIG расширения Python требуется как минимум Python 2.6. Python < 2.6 может собраться с небольшими изменениями в libwebp.swig или сгенерированном коде, но это не тестировалось.

Инструмент кодирования:

Каталог examples/ содержит инструменты для кодирования (cwebp) и декодирования (dwebp) изображений.

Самое простое использование должно выглядеть так: cwebp input.png -q 80 -o output.webp что преобразует входной файл в файл WebP, используя коэффициент качества 80 по шкале от 0 до 100 (0 — самое низкое качество, 100 — самое лучшее. Значение по умолчанию — 75). Вы также можете попробовать флаг -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

The main options you might want to try in order to further tune the visual quality are: -preset -sns -f -m

Namely:

  • 'preset' will set up a default encoding configuration targeting a particular type of input. It should appear first in the list of options, so that subsequent options can take effect on top of this preset. Default value is 'default'.
  • 'sns' will progressively turn on (when going from 0 to 100) some additional visual optimizations (like: segmentation map re-enforcement). This option will balance the bit allocation differently. It tries to take bits from the "easy" parts of the picture and use them in the "difficult" ones instead. Usually, raising the sns value (at fixed -q value) leads to larger files, but with better quality. Typical value is around '75'.
  • 'f' option directly links to the filtering strength used by the codec's in-loop processing. The higher the value, the smoother the highly-compressed area will look. This is particularly useful when aiming at very small files. Typical values are around 20-30. Note that using the option -strong/-nostrong will change the type of filtering. Use "-f 0" to turn filtering off.
  • 'm' controls the trade-off between encoding speed and quality. Default is 4. You can try -m 5 or -m 6 to explore more (time-consuming) encoding possibilities. A lower value will result in faster encoding at the expense of quality.

Инструмент декодирования:

В 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

Инструмент анализа файлов WebP:

'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

Сочетания клавиш: 'c' ................ переключить использование цветового профиля 'b' ................ переключить отображение фонового цвета 'i' ................ наложить информацию о файле 'd' ................ отключить смешивание и удаление (отладка) 'q' / 'Q' / ESC .... выход

Сборка:

Предварительные требования:

  1. OpenGL и OpenGL Utility Toolkit (GLUT) Linux: $ sudo apt-get install freeglut3-dev mesa-common-dev Mac + XCode:

    • Эти библиотеки должны быть доступны во фреймворках OpenGL / GLUT. Windows: http://freeglut.sourceforge.net/index.php#download
  2. (Опционально) qcms (Quick Color Management System) i. Загрузите qcms с Mozilla / Chromium: 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) Обновите пути include / library, чтобы они ссылались на каталог qcms.

Сборка с использованием 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

Note: if a single file name is passed as the argument, the arguments will be tokenized from this file. The file name must not start with the character '-'.

Конвертация анимированных GIF:

Анимированные GIF-файлы можно конвертировать в файлы WebP с анимацией, используя утилиту gif2webp, доступную в examples/. Затем файлы можно просматривать с помощью 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, gif2webp можно собрать, используя makefile.unix: $ make -f makefile.unix examples/gif2webp

или используя autoconf: $ ./configure --enable-everything $ make

Сравнение анимированных изображений:

Тестовая утилита anim_diff в examples/ может использоваться для сравнения двух анимированных изображений (каждое может быть 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

API кодирования:

Основные функции кодирования доступны в заголовочном файле 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. Единственный доступный параметр управления — это коэффициент качества.

Существуют также варианты для использования формата без потерь:

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 кодирования:

Более продвинутый 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

API декодирования:

В основном это одна функция, которую нужно вызвать:

#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 декодирования:

В случае постепенной передачи данных изображения всё равно можно декодировать инкрементально, используя несколько более сложный 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.

Он вернёт последнюю отображаемую строку пикселей.

Наконец, обратите внимание, что декодирование также может выполняться в предварительно выделенный буфер пикселей. Этот буфер необходимо передавать при создании WebPIDecoder, вызывая WebPINewRGB() или WebPINewYUVA().

Более подробную информацию смотрите в заголовочном файле src/webp/decode.h.

Расширенный API декодирования:

Декодирование WebP поддерживает расширенный API, обеспечивающий обрезку и масштабирование на лету, что чрезвычайно полезно в средах с ограниченной памятью, например на мобильных телефонах. По сути, использование памяти зависит от размера выходных данных, а не входных, когда нужен лишь быстрый предпросмотр или увеличенный фрагмент слишком большого изображения. Заодно можно сэкономить немного CPU.

-------------------------------------- BEGIN PSEUDO EXAMPLE // A) Init a configuration object WebPDecoderConfig config; CHECK(WebPInitDecoderConfig(&config));

root@kitploit:~
 // 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/

Обсуждение:

Эл. почта: [email protected] Веб: http://groups.google.com/a/webmproject.org/group/webp-discuss

Скачать инструмент