webp

package
v0.0.0-...-ec8f066 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2020 License: Apache-2.0 Imports: 10 Imported by: 1

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

View Source
const LosslessDefaultLevel int = 6
View Source
const LosslessDefaultQuality float32 = 70.0
View Source
const LossyDefaultQuality float32 = 75.0

Variables

View Source
var (
	ICCP = FourCC{'I', 'C', 'C', 'P'}
	XMP  = FourCC{'X', 'M', 'P', ' '}
	EXIF = FourCC{'E', 'X', 'I', 'F'}
)

Functions

func Decode

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

func DecodeConfig

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

func DecodeEX

func DecodeEX(r io.Reader, opts *DecodeOptions) (image.Image, error)

func DecodeSlice

func DecodeSlice(data []byte, opts *DecodeOptions) (image.Image, error)

func DeleteMetadata

func DeleteMetadata(img []byte, fourcc FourCC) error

return MuxNotFound if meta not exists

func Encode

func Encode(w io.Writer, img image.Image, opts *EncodeOptions) error

func EncodeBGR

func EncodeBGR(bgr []uint8, width, height, stride int, quality float32) ([]byte, error)

func EncodeBGRA

func EncodeBGRA(bgra []uint8, width, height, stride int, quality float32) ([]byte, error)

func EncodeLosslessBGR

func EncodeLosslessBGR(bgr []uint8, width, height, stride int) ([]byte, error)

func EncodeLosslessBGRA

func EncodeLosslessBGRA(bgra []uint8, width, height, stride int) ([]byte, error)

func EncodeLosslessRGB

func EncodeLosslessRGB(rgb []uint8, width, height, stride int) ([]byte, error)

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 EncodeLosslessRGBA(rgba []uint8, width, height, stride int) ([]byte, error)

func EncodeRGB

func EncodeRGB(rgb []uint8, width, height, stride int, quality float32) ([]byte, error)

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 EncodeRGBA(rgba []uint8, width, height, stride int, quality float32) ([]byte, error)

func EncodeSlice

func EncodeSlice(img image.Image, opts *EncodeOptions) ([]byte, error)

func GetMetadata

func GetMetadata(img []byte, fourcc FourCC) ([]byte, error)

return MuxNotFound if meta not exists

func SetMetadata

func SetMetadata(img []byte, fourcc FourCC, chunk []byte) ([]byte, error)

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 NewARGB

func NewARGB(r image.Rectangle) *ARGBImg

func (*ARGBImg) At

func (p *ARGBImg) At(x, y int) color.Color

func (*ARGBImg) Bounds

func (p *ARGBImg) Bounds() image.Rectangle

func (*ARGBImg) ColorModel

func (p *ARGBImg) ColorModel() color.Model

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 FourCC

type FourCC [4]byte

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
)

func (MuxError) Error

func (c MuxError) Error() string

type NYCbCrA

type NYCbCrA struct {
	image.NYCbCrA
}

webp yuva420

func NewNYCbCrA

func NewNYCbCrA(r image.Rectangle) *NYCbCrA

func (*NYCbCrA) At

func (p *NYCbCrA) At(x, y int) color.Color

func (*NYCbCrA) ColorModel

func (p *NYCbCrA) ColorModel() color.Model

func (*NYCbCrA) NYCbCrAAt

func (p *NYCbCrA) NYCbCrAAt(x, y int) colorx.NYCbCrBT601

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 NewRGB

func NewRGB(r image.Rectangle) *RGBImg

NewRGB returns a new RGBImg with the given bounds.

func (*RGBImg) At

func (p *RGBImg) At(x, y int) color.Color

func (*RGBImg) Bounds

func (p *RGBImg) Bounds() image.Rectangle

func (*RGBImg) ColorModel

func (p *RGBImg) ColorModel() color.Model

func (*RGBImg) RGBAAt

func (p *RGBImg) RGBAAt(x, y int) colorx.RGB

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

func (Version) Major

func (ver Version) Major() int

func (Version) Minor

func (ver Version) Minor() int

func (Version) Revision

func (ver Version) Revision() int

func (Version) String

func (ver Version) String() string

func (Version) V

func (ver Version) V() (major, minor, revision int)

type YCbCr

type YCbCr struct {
	image.YCbCr
}

webp yuv420

func NewYCbCr

func NewYCbCr(r image.Rectangle) *YCbCr

func (*YCbCr) At

func (p *YCbCr) At(x, y int) color.Color

func (*YCbCr) ColorModel

func (p *YCbCr) ColorModel() color.Model

func (*YCbCr) Set

func (p *YCbCr) Set(x, y int, c color.Color)

func (*YCbCr) YCbCrAt

func (p *YCbCr) YCbCrAt(x, y int) colorx.YCbCrBT601

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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