Documentation ¶
Overview ¶
Package webp provides a cgo binding of libwebp to process WebP image.
Require ¶
gcc
libwebp 1.1.0
Usage ¶
Encode lossy
var opts *webp.EncodeOptions //default options opts, _ = webp.NewEncOptions() //or init with preset opts, _ = webp.NewEncOptionsByPreset(webp.PresetPicture, webp.LossyDefaultQuality) var buf = bytes.NewBuffer(nil) err = webp.Encode(buf, img, opts) if err != nil { panic(err) } ioutil.WriteFile("foo_lossy.webp", buf.Bytes(), os.ModePerm)
Encode lossless
opts, _ := webp.NewEncOptions() opts.SetupLosslessPreset(webp.LosslessDefaultLevel) //or just opts.Lossless = true opts.Quality = webp.LosslessDefaultQuality //set true if you want preserve RGB values under transparent area opts.Exact = true var buf = bytes.NewBuffer(nil) err = webp.Encode(buf, img, opts) if err != nil { panic(err) } ioutil.WriteFile("foo_lossless.webp", buf.Bytes(), os.ModePerm)
Decode
fin, _ := os.Open("foo.webp") webpImg, err := webp.Decode(fin) if err != nil { panic(err) } fin.Seek(0, io.SeekStart) //decode with options decOpts := webp.NewDecOptions() decOpts.ImageType = webp.TypeNRGBA //decode as image.NRGBA webpImg, err = webp.DecodeEX(fin, options) if err != nil { panic(err) }
Get and Set metadata chunk
iccp, err := webp.GetMetadata(webpData, webp.ICCP) if err != nil { newWebpData, err := webp.SetMetadata(webpdata2, webp.ICCP, iccp) }
Index ¶
- Constants
- Variables
- func Decode(r io.Reader) (image.Image, error)
- func DecodeConfig(r io.Reader) (image.Config, error)
- func DecodeEX(r io.Reader, opts *DecodeOptions) (image.Image, error)
- func DecodeSlice(data []byte, opts *DecodeOptions) (image.Image, error)
- func DeleteMetadata(img []byte, fourcc FourCC) error
- func Encode(w io.Writer, img image.Image, opts *EncodeOptions) error
- func EncodeBGR(bgr []uint8, width, height, stride int, quality float32) ([]byte, error)
- func EncodeBGRA(bgra []uint8, width, height, stride int, quality float32) ([]byte, error)
- func EncodeLosslessBGR(bgr []uint8, width, height, stride int) ([]byte, error)
- func EncodeLosslessBGRA(bgra []uint8, width, height, stride int) ([]byte, error)
- func EncodeLosslessRGB(rgb []uint8, width, height, stride int) ([]byte, error)
- func EncodeLosslessRGBA(rgba []uint8, width, height, stride int) ([]byte, error)
- func EncodeRGB(rgb []uint8, width, height, stride int, quality float32) ([]byte, error)
- func EncodeRGBA(rgba []uint8, width, height, stride int, quality float32) ([]byte, error)
- func EncodeSlice(img image.Image, opts *EncodeOptions) ([]byte, error)
- func GetMetadata(img []byte, fourcc FourCC) ([]byte, error)
- func SetMetadata(img []byte, fourcc FourCC, chunk []byte) ([]byte, error)
- type ARGBImg
- type AlphaFilter
- type BitStreamFormat
- type BitstreamFeatures
- type DecCspMode
- type DecPixelFormat
- type DecodeOptions
- type EncodeOptions
- type EncodePreset
- type FilterType
- type FourCC
- type ImageHint
- type MuxError
- type NYCbCrA
- type RGBImg
- type VP8DecodeError
- type VP8EncodeError
- type VP8StatusCode
- type Version
- type YCbCr
Constants ¶
const LosslessDefaultLevel int = 6
const LosslessDefaultQuality float32 = 70.0
const LossyDefaultQuality float32 = 75.0
Variables ¶
var ( ICCP = FourCC{'I', 'C', 'C', 'P'} XMP = FourCC{'X', 'M', 'P', ' '} EXIF = FourCC{'E', 'X', 'I', 'F'} )
Functions ¶
func DecodeSlice ¶
func DecodeSlice(data []byte, opts *DecodeOptions) (image.Image, error)
func DeleteMetadata ¶
return MuxNotFound if meta not exists
func EncodeBGRA ¶
func EncodeLosslessBGR ¶
func EncodeLosslessBGRA ¶
func EncodeLosslessRGB ¶
These functions are the equivalent of the above, but compressing in a lossless manner. Files are usually larger than lossy format, but will not suffer any compression loss. Note these functions, like the lossy versions, use the library's default settings. For lossless this means 'exact' is disabled. RGB values in transparent areas will be modified to improve compression. To avoid this, use Encode(w io.Writer, img image.Image, opts *EncodeOptions) and set EncodeOptions exact to 1.
func EncodeLosslessRGBA ¶
func EncodeRGB ¶
These functions compress using the lossy format, and the quality_factor can go from 0 (smaller output, lower quality) to 100 (best quality, larger output).
func EncodeRGBA ¶
func EncodeSlice ¶
func EncodeSlice(img image.Image, opts *EncodeOptions) ([]byte, error)
func GetMetadata ¶
return MuxNotFound if meta not exists
Types ¶
type ARGBImg ¶
type ARGBImg struct { // Pix holds the image's pixels, store A,R,G,B from hi to lo in uint32 Pix []uint32 // Stride is the Pix stride in pixels units, not bytes between vertically adjacent pixels. Stride int // Rect is the image's bounds. Rect image.Rectangle }
encode helper for someone want to import custom image type self
func (*ARGBImg) ColorModel ¶
type AlphaFilter ¶
type AlphaFilter int
const ( NoneAlphaFilter AlphaFilter = iota FastAlphaFilter BestAlphaFilter )
type BitStreamFormat ¶
type BitStreamFormat int
const ( FormatMixed BitStreamFormat = iota FormatLossy FormatLossless )
type BitstreamFeatures ¶
type BitstreamFeatures struct {
Width, Height int
Format BitStreamFormat
HasAlpha bool
HasAnimation bool
}
func GetBitstreamFeatures ¶
func GetBitstreamFeatures(data []byte) (*BitstreamFeatures, error)
type DecCspMode ¶
type DecCspMode int
const ( ModeRGB DecCspMode = C.MODE_RGB ModeRGBA DecCspMode = C.MODE_rgbA ModeNRGBA DecCspMode = C.MODE_RGBA ModeYUV DecCspMode = C.MODE_YUV ModeYUVA DecCspMode = C.MODE_YUVA )
type DecPixelFormat ¶
type DecPixelFormat func(config *C.WebPDecoderConfig, w, h int) image.Image
var ( // auto detect decoded image type, return webp.YCbCr/webp.NYCbCrA for lossy webp, otherwise webp.RGBImg/image.NRGBA TypeAuto DecPixelFormat = decPixAuto // auto detect decoded image type, return image.NRGBA if has alpha, otherwise image.RGBA TypeStd DecPixelFormat = decPixStd TypeRGB DecPixelFormat = decPixRGB TypeRGBA DecPixelFormat = decPixRGBA TypeNRGBA DecPixelFormat = decPixNRGBA TypeYUV DecPixelFormat = decPixYUV TypeYUVA DecPixelFormat = decPixYUVA )
type DecodeOptions ¶
type DecodeOptions struct { BypassFiltering bool // if true, skip the in-loop filtering NoFancyUpsampling bool // if true, use faster pointwise upsampler Crop image.Rectangle // do cropping if not empty, this is applied _first_ Scale image.Rectangle // do scaling if not empty, this is applied _afterward_ UseThreads bool // if true, use multi-threaded decoding DitheringStrength int // dithering strength (0=Off, 100=full) Flip bool // flip output vertically AlphaDitheringStrength int // alpha dithering strength in [0..100] ImageType DecPixelFormat // decoded image type }
func NewDecOptions ¶
func NewDecOptions() *DecodeOptions
type EncodeOptions ¶
type EncodeOptions struct { Lossless bool // 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. Quality float32 // quality/speed trade-off (0=fast, 6=slower-better) Method int // Hint for image type (lossless only for now) ImageHint ImageHint // if non-zero, set the desired target size in bytes. Takes precedence over the 'compression' parameter. TargetSize int // if non-zero, specifies the minimal distortion to try to achieve. Takes precedence over target_size TargetPSNR float32 // maximum number of segments to use, in [1..4] Segments int // Spatial Noise Shaping. 0=off, 100=maximum SnsStrength int // range: [0 = off .. 100 = strongest] FilterStrength int // range: [0 = off .. 7 = least sharp] FilterSharpness int // filtering type: 0 = simple, 1 = strong (only used if filter_strength > 0 or autofilter > 0) FilterType FilterType // Auto adjust filter's strength AutoFilter bool // Algorithm for encoding the alpha plane (0 = none, 1 = compressed with WebP lossless). Default is 1 AlphaCompression int // Predictive filtering method for alpha plane. 0: none, 1: fast, 2: best. Default if 1. AlphaFiltering AlphaFilter // Between 0 (smallest size) and 100 (lossless). Default is 100. AlphaQuality int // number of entropy-analysis passes (in [1..10]). Pass int // if true, export the compressed picture back. In-loop filtering is not applied. ShowCompressed bool // preprocessing filter: 0=none, 1=segment-smooth, 2=pseudo-random dithering Preprocessing int // log2(number of token partitions) in [0..3]. Default is set to 0 for easier progressive decoding. Partitions int // quality degradation allowed to fit the 512k limit on prediction modes coding (0: no degradation, 100: maximum possible degradation). PartitionLimit int // If true, compression parameters will be remapped // to better match the expected output size from // JPEG compression. Generally, the output size will // be similar but the degradation will be lower. EmulateJpegSize bool // If true, try and use multi-threaded encoding. ThreadLevel bool // If set, reduce memory usage (but increase CPU use). LowMemory bool // Near lossless encoding [0 = max loss .. 100 = off // (default)]. NearLossless int // if true, preserve the exact RGB values under // transparent area. Otherwise, discard this invisible // RGB information for better compression. The default // value is 0. Exact bool // reserved for future lossless feature UseDeltaPalette int // if needed, use sharp (and slow) RGB->YUV conversion UseSharpYUV bool }
func NewEncOptions ¶
func NewEncOptions() (*EncodeOptions, error)
func NewEncOptionsByPreset ¶
func NewEncOptionsByPreset(preset EncodePreset, quality float32) (*EncodeOptions, error)
func (*EncodeOptions) SetupLosslessPreset ¶
func (opts *EncodeOptions) SetupLosslessPreset(level int) error
Activate the lossless compression mode with the desired efficiency level between 0 (fastest, lowest compression) and 9 (slower, best compression). A good default level is '6', providing a fair tradeoff between compression speed and final compressed size. This function will overwrite several fields from config: 'method', 'quality' and 'lossless'.
func (*EncodeOptions) Validate ¶
func (opts *EncodeOptions) Validate() error
type EncodePreset ¶
type EncodePreset int
const ( PresetDefault EncodePreset = C.WEBP_PRESET_DEFAULT // default preset. PresetPicture EncodePreset = C.WEBP_PRESET_PICTURE // digital picture, like portrait, inner shot PresetPhoto EncodePreset = C.WEBP_PRESET_PHOTO // outdoor photograph, with natural lighting PresetDrawing EncodePreset = C.WEBP_PRESET_DRAWING // hand or line drawing, with high-contrast details PresetIcon EncodePreset = C.WEBP_PRESET_ICON // small-sized colorful images PresetText EncodePreset = C.WEBP_PRESET_TEXT // text-like )
type FilterType ¶
type FilterType int
const ( SimpleFilter FilterType = 0 StrongFilter FilterType = 1 )
type ImageHint ¶
type ImageHint int
const ( HintDefault ImageHint = C.WEBP_HINT_DEFAULT // default preset. HintPicture ImageHint = C.WEBP_HINT_PICTURE // digital picture, like portrait, inner shot HintPhoto ImageHint = C.WEBP_HINT_PHOTO // outdoor photograph, with natural lighting HintGraph ImageHint = C.WEBP_HINT_GRAPH // Discrete tone image (graph, map-tile etc). HintLast ImageHint = C.WEBP_HINT_LAST )
type MuxError ¶
type MuxError int
const ( MuxOk MuxError = C.WEBP_MUX_OK MuxNotFound MuxError = C.WEBP_MUX_NOT_FOUND MuxInvalidArgument MuxError = C.WEBP_MUX_INVALID_ARGUMENT MuxBadData MuxError = C.WEBP_MUX_BAD_DATA MuxMemoryError MuxError = C.WEBP_MUX_MEMORY_ERROR MuxNotEnoughData MuxError = C.WEBP_MUX_NOT_ENOUGH_DATA )
type RGBImg ¶
type RGBImg struct { // Pix holds the image's pixels, in R, G, B order. Pix []uint8 // Stride is the Pix stride (in bytes) between vertically adjacent pixels. Stride int // Rect is the image's bounds. Rect image.Rectangle }
func (*RGBImg) ColorModel ¶
type VP8DecodeError ¶
type VP8DecodeError string
func (VP8DecodeError) Error ¶
func (e VP8DecodeError) Error() string
type VP8EncodeError ¶
type VP8EncodeError int
const ( VP8EncOk VP8EncodeError = C.VP8_ENC_OK VP8EncErrorOutOfMemory VP8EncodeError = C.VP8_ENC_ERROR_OUT_OF_MEMORY VP8EncErrorBitstreamOutOfMemory VP8EncodeError = C.VP8_ENC_ERROR_BITSTREAM_OUT_OF_MEMORY VP8EncErrorNullParameter VP8EncodeError = C.VP8_ENC_ERROR_NULL_PARAMETER VP8EncErrorInvalidConfiguration VP8EncodeError = C.VP8_ENC_ERROR_INVALID_CONFIGURATION VP8EncErrorBadDimension VP8EncodeError = C.VP8_ENC_ERROR_BAD_DIMENSION VP8EncErrorPartition0Overflow VP8EncodeError = C.VP8_ENC_ERROR_PARTITION0_OVERFLOW VP8EncErrorPartitionOverflow VP8EncodeError = C.VP8_ENC_ERROR_PARTITION_OVERFLOW VP8EncErrorBadWrite VP8EncodeError = C.VP8_ENC_ERROR_BAD_WRITE VP8EncErrorFileTooBig VP8EncodeError = C.VP8_ENC_ERROR_FILE_TOO_BIG VP8EncErrorUserAbort VP8EncodeError = C.VP8_ENC_ERROR_USER_ABORT VP8EncErrorLast VP8EncodeError = C.VP8_ENC_ERROR_LAST )
func (VP8EncodeError) Error ¶
func (e VP8EncodeError) Error() string
func (VP8EncodeError) String ¶
func (e VP8EncodeError) String() string
type VP8StatusCode ¶
type VP8StatusCode int
const ( VP8StatusOk VP8StatusCode = C.VP8_STATUS_OK VP8StatusOutOfMemory VP8StatusCode = C.VP8_STATUS_OUT_OF_MEMORY VP8StatusInvalidParam VP8StatusCode = C.VP8_STATUS_INVALID_PARAM VP8StatusBitstreamError VP8StatusCode = C.VP8_STATUS_BITSTREAM_ERROR VP8StatusUnsupportedFeature VP8StatusCode = C.VP8_STATUS_UNSUPPORTED_FEATURE VP8StatusSuspended VP8StatusCode = C.VP8_STATUS_SUSPENDED VP8StatusUserAbort VP8StatusCode = C.VP8_STATUS_USER_ABORT VP8StatusNotEnoughData VP8StatusCode = C.VP8_STATUS_NOT_ENOUGH_DATA )
func (VP8StatusCode) String ¶
func (c VP8StatusCode) String() string
type Version ¶
type Version int
func DecoderVersion ¶
func DecoderVersion() Version
func EncoderVersion ¶
func EncoderVersion() Version