webp

package module
v0.0.0-...-b9fdadd Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-webp

purego で libwebp・libwebpdemux・libwebpmux の共有ライブラリを動的に読み込む、CGo 不要の WebP デコーダー / エンコーダーです。

libwebp のインストール(vcpkg)

vcpkg なら、どの OS でも同じ手順でインストールできます。

OS 共有ライブラリ トリプレット 置き場所($VCPKG_ROOT/installed/<トリプレット>/) 検索パス
Windows libwebp.dll、libwebpdemux.dll、libwebpmux.dll x64-windows / arm64-windows bin PATH
Linux libwebp.so、libwebpdemux.so、libwebpmux.so x64-linux-dynamic / arm64-linux-dynamic lib LD_LIBRARY_PATH
macOS libwebp.dylib、libwebpdemux.dylib、libwebpmux.dylib arm64-osx-dynamic / x64-osx-dynamic(Intel) lib DYLD_LIBRARY_PATH
  • 3 つとも必要です。vcpkg の libwebp は既定の feature で libwebpmux(EncodeAll が使うアニメーションエンコーダー)も作ります。
  • 共有ライブラリにする: Linux / macOS の既定のトリプレット(x64-linux、arm64-osx など)は静的ライブラリを作り、purego から読み込めないため *-dynamic を使います。Windows の x64-windows は最初から DLL を作ります。

インストール後、上の置き場所を検索パスに追加します(永続化するなら ~/.bashrc / ~/.zshrc などに書きます)。

Windows(Visual Studio または Build Tools の「C++ によるデスクトップ開発」が必要)

vcpkg install libwebp:x64-windows
$env:PATH = "$env:VCPKG_ROOT\installed\x64-windows\bin;$env:PATH"   # 現在のセッションのみ
# ユーザー環境変数に永続的に追加(新しいターミナルから有効)
[Environment]::SetEnvironmentVariable("PATH", "$env:VCPKG_ROOT\installed\x64-windows\bin;" + [Environment]::GetEnvironmentVariable("PATH", "User"), "User")

bin には依存 DLL の libsharpyuv.dll も入ります。配布時はこれらを実行ファイルと同じディレクトリに置けば PATH の設定は不要です。

Linux(例は Debian / Ubuntu)

sudo apt install build-essential cmake ninja-build pkg-config curl zip unzip tar git
vcpkg install libwebp:x64-linux-dynamic
export LD_LIBRARY_PATH="$VCPKG_ROOT/installed/x64-linux-dynamic/lib:$LD_LIBRARY_PATH"

vcpkg を使わず sudo apt install libwebp-dev でも 3 つの .so が標準の検索パスに入ります。

macOS

xcode-select --install
brew install cmake ninja pkg-config
vcpkg install libwebp:arm64-osx-dynamic
export DYLD_LIBRARY_PATH="$VCPKG_ROOT/installed/arm64-osx-dynamic/lib:$DYLD_LIBRARY_PATH"

DYLD_* は SIP により /bin/sh などのシステム付属プログラムを経由すると消えるため、シェルスクリプトや make から実行する場合はスクリプト内で再度 export してください。

インストールの確認

検索パスを設定したターミナルでリポジトリのルートから go test -count=1 -v . を実行し、すべて --- PASS になれば読み込み・デコード・エンコードができています。ライブラリがないとスキップではなく --- FAIL になります(libwebp を使わないオプション検証・画素変換・構造体レイアウトのテストを除く)。

出力 原因と対処
libwebp is required by this test: webp: cannot load library ... 共有ライブラリが見つかりません。検索パスを確認してください。libwebpmux だけ見つからない場合は feature なしでビルドされています。
TestLibrary: ... want 1.x libwebp 1.x 以外が先に見つかっています。vcpkg のディレクトリを先にしてください。

TestLibrary は libwebp・libwebpdemux・libwebpmux のバージョンを -v でログに出します。

自分のプログラムからは webp.Dynamic() で確認できます。

if err := webp.Dynamic(); err != nil {
    log.Fatal("共有ライブラリが見つかりません:", err)
}
cwebp のインストール(任意)

このパッケージの実行には不要ですが、Options と同じ設定で cwebp の出力と比べたいときは、cwebp feature を付けて入れ直します(既定の feature はそのまま残り、再ビルドされます)。

vcpkg install "libwebp[cwebp]:x64-windows"        # Windows
vcpkg install "libwebp[cwebp]:x64-linux-dynamic"  # Linux
vcpkg install "libwebp[cwebp]:arm64-osx-dynamic"  # macOS

cwebp は $VCPKG_ROOT/installed/<トリプレット>/tools/libwebp/ に入ります。cwebp -version で、TestLibrary が出す libwebp のバージョンと一致することを確認してください。

使い方

import "github.com/f0reth/go-webp"

img, err := webp.Decode(f)     // WebP → image.Image(アニメーションは先頭フレーム)
ret, err := webp.DecodeAll(f)  // ret.Image は各フレーム、ret.Delay は各フレームの表示時間(ミリ秒)、ret.LoopCount はループ回数(0 = 無限)
err = webp.Encode(w, img, nil) // image.Image → WebP(nil はデフォルト設定)

デコードした画像は、アルファがあれば *image.NRGBA(非乗算済み、libwebp の出力そのまま)、なければ *image.RGBA です。image.Decode / image.DecodeConfig からも使えます。

エンコードオプション

Options は cwebp と同じ設定・デフォルト値を持ち、nil やゼロ値のフィールドは cwebp のデフォルトになります。0 が意味を持つ Quality / AlphaQuality / Method / NearLossless はポインタなので new(80) のように指定します。範囲外の値は ErrOptions になります。

err := webp.Encode(w, img, &webp.Options{
    Quality:  new(80),           // -q 0〜100(デフォルト: 75)
    Method:   new(6),            // -m 0(速い)〜6(高圧縮、デフォルト: 4)
    Preset:   webp.PresetPhoto,  // -preset(他のオプションより先に適用)
    SharpYUV: true,              // -sharp_yuv
})

err = webp.Encode(w, img, &webp.Options{Lossless: true}) // 可逆圧縮。Quality は圧縮の手間(大きいほど小さく遅い)
cwebp / img2webp Options
-preset Preset
-q Quality
-alpha_q AlphaQuality
-m Method
-lossless Lossless
-near_lossless NearLossless(Lossless を含む)
-exact Exact
-sharp_yuv SharpYUV
-size / -psnr TargetSize / TargetPSNR(非可逆のみ。cwebp と同じく -pass 6 で探索)
img2webp -mixed / -min_size AllowMixed / MinimizeSize(EncodeAll のみ)
img2webp -loop / -d WEBP.LoopCount / WEBP.Delay
  • マルチスレッド(cwebp -mt)は常に有効です。
  • *image.NRGBA と不透明な *image.RGBA はコピーせずに libwebp に渡し、半透明の *image.RGBA は非乗算済みに、その他の画像は image/draw で変換します。16bit の画像は 8bit になります。
  • -metadata、-crop、-resize、-blend_alpha などの前処理は非対応です。

EncodeAll は複数枚の画像をアニメーション WebP にします(img2webp と同じ)。全フレームが先頭と同じサイズで、Delay が Image と同じ数だけ必要です。1 フレームだけなら静止画になります。

err := webp.EncodeAll(w, &webp.WEBP{Image: frames, Delay: delays, LoopCount: 0}, &webp.Options{Lossless: true})

ベンチマーク

テストと同じ環境で実行します。

go test -run '^$' -bench . -benchmem .
go test -run '^$' -bench . -count 10 . > new.txt   # 変更前の old.txt と benchstat old.txt new.txt で比較

ns/op に加えて 1 秒あたりの処理画素数(Mpx/s、アニメーションは全フレーム分)を、エンコードはさらに出力サイズ(out-bytes)と 1 画素あたりのビット数(bpp)を出力します。

ベンチマーク 内容
BenchmarkDecode 512x512 の写真の非可逆 / アルファ付き非可逆 / 可逆、アニメーションの先頭フレームのデコード
BenchmarkDecodeConfig ヘッダーの解析のみ
BenchmarkDecodeAll アニメーション(500x360、17 フレーム)全体のデコード
BenchmarkEncode 512x512 の写真のエンコード。デフォルト、アルファ、品質 90、シャープ YUV、目標サイズ、可逆、ニアロスレス、メソッド 0/2/4/6
BenchmarkConvert PNG / JPEG(品質 90)から WebP への変換(標準ライブラリでのデコードを含む)
BenchmarkEncodeAll アニメーション全体の非可逆 / 可逆エンコード
BenchmarkDecodeParallel / BenchmarkEncodeParallel 複数ゴルーチンからの同時デコード / エンコード
BenchmarkRGBAFromImage image.Image から libwebp 用 RGBA バッファへの Go 側の変換(画像の型ごと、libwebp 不要)

Documentation

Overview

Package webp implements a WebP image decoder and encoder based on the libwebp, libwebpdemux and libwebpmux shared libraries used via purego (CGo-free).

Index

Constants

View Source
const (
	// DefaultQuality is the default quality (cwebp -q).
	DefaultQuality = 75
	// DefaultAlphaQuality is the default quality of the alpha channel (cwebp -alpha_q).
	DefaultAlphaQuality = 100
	// DefaultMethod is the default compression method (cwebp -m).
	DefaultMethod = 4
)

Defaults of the encoding parameters. They are the same as the defaults of cwebp.

Variables

View Source
var (
	ErrDecode  = errors.New("webp: decode failed")
	ErrEncode  = errors.New("webp: encode failed")
	ErrOptions = errors.New("webp: invalid options")
)

Errors returned by this package, wrapped with details.

Functions

func Decode

func Decode(r io.Reader) (image.Image, error)

Decode reads a WebP image from r and returns it as an image.Image. For an animation, it returns the first frame.

func DecodeConfig

func DecodeConfig(r io.Reader) (image.Config, error)

DecodeConfig returns the color model and dimensions of a WebP image without decoding it.

func Dynamic

func Dynamic() error

Dynamic returns the error, if any, that makes the libwebp shared libraries unusable.

func Encode

func Encode(w io.Writer, m image.Image, o *Options) error

Encode writes the image m to w with the given options; nil options mean the defaults.

func EncodeAll

func EncodeAll(w io.Writer, a *WEBP, o *Options) error

EncodeAll writes the frames of a to w as an animation with the given options; nil options mean the defaults. Every frame must have the size of the first one and a delay in milliseconds. A single frame is encoded as a still image, like img2webp does.

Types

type Options

type Options struct {
	// Preset applied before the other options (cwebp -preset). Default: PresetDefault.
	Preset Preset
	// Quality in [0,100] (cwebp -q). Default: 75. In lossless mode it is the compression effort:
	// higher values give smaller files, more slowly.
	Quality *int
	// Quality of the alpha channel in [0,100] where 100 is lossless (cwebp -alpha_q). Default: 100.
	AlphaQuality *int
	// Compression method in [0,6] where 0 is the fastest and 6 the slowest with the best
	// compression (cwebp -m). Default: 4.
	Method *int
	// Encode losslessly (cwebp -lossless).
	Lossless bool
	// Near-lossless preprocessing level in [0,100] where 0 is the strongest and 100 is off
	// (cwebp -near_lossless). Setting it implies Lossless.
	NearLossless *int
	// Preserve the RGB values of transparent pixels (cwebp -exact). By default they are changed
	// for a better compression.
	Exact bool
	// Use the sharper and slower RGB to YUV conversion (cwebp -sharp_yuv).
	SharpYUV bool
	// Target size in bytes (cwebp -size). 0 disables it. Lossy only.
	TargetSize int
	// Target PSNR in dB (cwebp -psnr). It takes precedence over TargetSize. 0 disables it.
	// Lossy only.
	TargetPSNR float64

	// EncodeAll only: encode every frame both lossy and lossless and keep the smaller one
	// (img2webp -mixed).
	AllowMixed bool
	// EncodeAll only: minimize the output size, slowly (img2webp -min_size).
	MinimizeSize bool
}

Options are the encoding parameters. They mirror the options of cwebp, and of img2webp for EncodeAll, with the same defaults. The zero value of every field means "use the cwebp default". Fields that accept 0 as a meaningful value are pointers, e.g. Quality: new(80).

type Preset

type Preset int

Preset is a set of encoding parameters tuned for a kind of image (cwebp -preset).

const (
	PresetDefault Preset = iota
	// PresetPicture is for digital pictures, like portraits or inner shots.
	PresetPicture
	// PresetPhoto is for outdoor photographs, with natural lighting.
	PresetPhoto
	// PresetDrawing is for hand or line drawings, with high-contrast details.
	PresetDrawing
	// PresetIcon is for small-sized colorful images.
	PresetIcon
	// PresetText is for text-like images.
	PresetText
)

Presets, in the order of the WebPPreset enum of libwebp.

type WEBP

type WEBP struct {
	// Images, one per frame. Decoded images are *image.NRGBA when the WebP has alpha and
	// *image.RGBA otherwise.
	Image []image.Image
	// Display durations, one per frame, in milliseconds.
	Delay []int
	// Number of times an animation is played, 0 meaning infinitely.
	LoopCount int
}

WEBP represents the possibly multiple images stored in a WebP file.

func DecodeAll

func DecodeAll(r io.Reader) (*WEBP, error)

DecodeAll reads a WebP image from r and returns the frames of the animation and their timing information. A still image is returned as a single frame.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址