Documentation
¶
Overview ¶
Package anywebp 把任意常见格式的图片转换为 WebP。
特性一览:
- 输入格式:JPEG / PNG / GIF(取首帧)/ WebP / BMP / TIFF / HEIC·HEIF(依赖系统工具);
- 三种压缩模式:近无损(默认,视觉无损且体积小)、严格无损、自定义质量有损;
- 可选最长边缩放,自动剥离 EXIF 等全部元数据(重新编码天然实现);
- 解码前做像素尺寸安全检查,防御解压炸弹。
快速上手:
webpBytes, err := anywebp.Convert(jpegBytes, nil) // nil 使用默认近无损模式
更多用法见 README。
Index ¶
- Constants
- Variables
- func Convert(data []byte, opt *Options) ([]byte, error)
- func ConvertFile(src, dst string, opt *Options) (string, error)
- func ConvertImage(img image.Image, opt *Options) ([]byte, error)
- func ConvertReader(r io.Reader, w io.Writer, opt *Options) error
- func DetectFormat(data []byte) (string, error)
- type Mode
- type Options
Constants ¶
View Source
const (
// DefaultLossyQuality ModeLossy 模式的默认质量。
DefaultLossyQuality = 80
)
默认参数常量。
Variables ¶
View Source
var ( // ErrUnsupportedFormat 输入不是可识别的图片格式,或内容已损坏。 ErrUnsupportedFormat = errors.New("anywebp: 不支持的图片格式或文件已损坏") // ErrImageTooLarge 图片像素尺寸超出安全上限。 ErrImageTooLarge = errors.New("anywebp: 图片像素尺寸超出安全上限") // ErrEmptyInput 输入内容为空。 ErrEmptyInput = errors.New("anywebp: 输入内容为空") )
对外错误定义,调用方可用 errors.Is 判断。
Functions ¶
func Convert ¶
Convert 把任意支持格式的图片字节转换为 WebP 字节。
完整流程:
- 嗅探格式(HEIC/HEIF 先经系统工具转为 PNG);
- DecodeConfig 检查像素尺寸(防解压炸弹);
- 完整解码(动图取首帧);
- 按需等比缩放;
- 重新编码为 WebP(自动剥离全部元数据)。
func ConvertFile ¶
ConvertFile 文件接口:读取 src 图片文件,转换后写入 dst。 dst 为空时自动取 src 同目录同名的 .webp 路径,返回实际输出路径。
func ConvertImage ¶
ConvertImage 把已解码的 image.Image 编码为 WebP 字节。 适合调用方自己持有 image.Image 的场景(如截图、绘图程序)。
func ConvertReader ¶
ConvertReader 流式接口:从 r 读取任意格式图片,向 w 写出 WebP。
func DetectFormat ¶
DetectFormat 嗅探图片格式,返回小写格式名: jpeg / png / gif / webp / bmp / tiff / heic;无法识别返回 ErrUnsupportedFormat。
Types ¶
type Options ¶
type Options struct {
// Mode 压缩模式,默认 ModeNearLossless。
Mode Mode
// Quality 有损质量(1-100),仅 ModeLossy 生效;0 表示使用 DefaultLossyQuality。
Quality float32
// MaxDimension 最长边上限(像素)。
// 大于 0 时,超出的图片会等比缩小到该尺寸;0 表示不缩放。
MaxDimension int
// Exact 严格无损时是否保留全透明像素的原始 RGB 值。
// 默认 false(透明区域 RGB 可被优化以减小体积)。
Exact bool
}
Options 转换选项。传 nil 等价于 &Options{}(全部默认值)。
Click to show internal directories.
Click to hide internal directories.