This repository has been archived by the owner on Feb 25, 2021. It is now read-only.
forked from chai2010/webp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
91 lines (85 loc) · 1.97 KB
/
writer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2014 <chaishushan{AT}gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package webp
import (
"image"
"image/color"
"io"
)
const DefaulQuality = 90
// Options are the encoding parameters.
type Options struct {
Lossless bool
Quality float32 // 0 ~ 100
}
// Encode writes the image m to w in WEBP format.
func Encode(w io.Writer, m image.Image, opt *Options) (err error) {
var output []byte
if opt != nil && opt.Lossless {
switch m := adjustImage(m).(type) {
case *image.Gray:
if output, err = EncodeLosslessGray(m); err != nil {
return
}
case *_RGB:
if output, err = EncodeLosslessRGB(m); err != nil {
return
}
case *image.RGBA:
if output, err = EncodeLosslessRGBA(m); err != nil {
return
}
default:
panic("image/webp: Encode, unreachable!")
}
} else {
quality := float32(DefaulQuality)
if opt != nil {
quality = opt.Quality
}
switch m := adjustImage(m).(type) {
case *image.Gray:
if output, err = EncodeGray(m, quality); err != nil {
return
}
case *_RGB:
if output, err = EncodeRGB(m, quality); err != nil {
return
}
case *image.RGBA:
if output, err = EncodeRGBA(m, quality); err != nil {
return
}
default:
panic("image/webp: Encode, unreachable!")
}
}
_, err = w.Write(output)
return
}
func adjustImage(m image.Image) image.Image {
if x, ok := m.(Image); ok {
m = x.BaseType()
}
switch m := m.(type) {
case *image.Gray, *image.RGBA, *_RGB:
return m
default:
b := m.Bounds()
rgba := image.NewRGBA(b)
dstColorRGBA64 := &color.RGBA64{}
dstColor := color.Color(dstColorRGBA64)
for y := b.Min.Y; y < b.Max.Y; y++ {
for x := b.Min.X; x < b.Max.X; x++ {
pr, pg, pb, pa := m.At(x, y).RGBA()
dstColorRGBA64.R = uint16(pr)
dstColorRGBA64.G = uint16(pg)
dstColorRGBA64.B = uint16(pb)
dstColorRGBA64.A = uint16(pa)
rgba.Set(x, y, dstColor)
}
}
return rgba
}
}