forked from rai-project/image
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jpeg.go
90 lines (80 loc) · 2.44 KB
/
jpeg.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
// +build cgo,!nolibjpeg
package image
import (
"image"
"image/gif"
"image/png"
"io"
"strings"
"github.com/pkg/errors"
libjpeg "github.com/c3sr/go-libjpeg"
"github.com/c3sr/image/types"
"golang.org/x/image/bmp"
)
func getDCTMethod(method string) (libjpeg.DCTMethod, error) {
switch strings.ToLower(method) {
case "slow", "integer_accurate", "dctislow":
return libjpeg.DCTISlow, nil
case "fast", "integer_fast", "dctifast":
return libjpeg.DCTIFast, nil
case "float", "dctfloat":
return libjpeg.DCTFloat, nil
default:
var none libjpeg.DCTMethod
return none, errors.Errorf("the DCT method %v specified is not valid", method)
}
}
func jpegDecoder(options *Options) func(io.Reader) (image.Image, error) {
return func(r io.Reader) (image.Image, error) {
dctMethod, err := getDCTMethod(options.dctMethod)
if err != nil {
return nil, err
}
mode := options.mode
decodeOpts := &libjpeg.DecoderOptions{
DCTMethod: dctMethod,
DisableFancyUpsampling: true,
// DisableBlockSmoothing: true,
}
if mode == types.RGBMode || mode == types.BGRMode {
res, err := libjpeg.DecodeIntoRGB(r, decodeOpts)
return &types.RGBImage{res.Pix, res.Stride, res.Rect}, err
}
return libjpeg.Decode(r, decodeOpts)
}
}
func getDecoder(format string, options *Options) (func(io.Reader) (image.Image, error), error) {
if format == "jpeg" && options.resizeWidth != 0 && options.resizeHeight != 0 {
// if runtime.GOARCH == "ppc64le" {
// return jpeg.Decode, nil
// }
return func(r io.Reader) (image.Image, error) {
mode := options.mode
dctMethod, err := getDCTMethod(options.dctMethod)
if err != nil {
return nil, err
}
decodeOpts := &libjpeg.DecoderOptions{
ScaleTarget: image.Rect(0, 0, options.resizeWidth, options.resizeHeight),
DCTMethod: dctMethod,
DisableFancyUpsampling: true,
// DisableBlockSmoothing: true,
}
if mode == types.RGBMode || mode == types.BGRMode {
res, err := libjpeg.DecodeIntoRGB(r, decodeOpts)
return &types.RGBImage{res.Pix, res.Stride, res.Rect}, err
}
return libjpeg.Decode(r, decodeOpts)
}, nil
}
imageFormatDecoders := map[string]func(io.Reader) (image.Image, error){
"jpeg": jpegDecoder(options),
"png": png.Decode,
"gif": gif.Decode,
"bmp": bmp.Decode,
}
if decoder, ok := imageFormatDecoders[format]; ok {
return decoder, nil
}
return nil, errors.Errorf("format %v is not supported", format)
}