@@ -91,7 +91,6 @@ func ResizeImage(img image.Image, width, height uint) image.Image {
91
91
return resizedImg
92
92
}
93
93
94
- // 压缩图像为指定的大小, 返回格式为JPEG
95
94
func CompressImage (input []byte , maxSizeMB , maxEdgeLength uint ) ([]byte , error ) {
96
95
img , _ , err := image .Decode (bytes .NewReader (input ))
97
96
if err != nil {
@@ -100,8 +99,8 @@ func CompressImage(input []byte, maxSizeMB, maxEdgeLength uint) ([]byte, error)
100
99
bounds := img .Bounds ()
101
100
width := bounds .Dx ()
102
101
height := bounds .Dy ()
102
+ var newWidth , newHeight uint
103
103
if width > int (maxEdgeLength ) || height > int (maxEdgeLength ) {
104
- var newWidth , newHeight uint
105
104
if width > height {
106
105
newWidth = maxEdgeLength
107
106
newHeight = uint (float64 (height ) * (float64 (maxEdgeLength ) / float64 (width )))
@@ -113,26 +112,26 @@ func CompressImage(input []byte, maxSizeMB, maxEdgeLength uint) ([]byte, error)
113
112
}
114
113
quality := 100
115
114
var buf bytes.Buffer
116
- if len ( input ) < int ( maxSizeMB * 1024 * 1024 ) {
117
- err := jpeg . Encode ( & buf , img , & jpeg. Options { Quality : quality })
118
- if err != nil {
119
- return nil , err
120
- }
115
+ err = jpeg . Encode ( & buf , img , & jpeg. Options { Quality : quality })
116
+ if err != nil {
117
+ return nil , err
118
+ }
119
+ if buf . Len () < int ( maxSizeMB * 1024 * 1024 ) {
121
120
return buf .Bytes (), nil
122
121
}
123
122
for {
123
+ if quality <= 0 {
124
+ return nil , fmt .Errorf ("cannot compress image to %d MB" , maxSizeMB )
125
+ }
126
+ quality -= 5
124
127
buf .Reset ()
125
- err : = jpeg .Encode (& buf , img , & jpeg.Options {Quality : quality })
128
+ err = jpeg .Encode (& buf , img , & jpeg.Options {Quality : quality })
126
129
if err != nil {
127
130
return nil , err
128
131
}
129
132
if buf .Len () < int (maxSizeMB * 1024 * 1024 ) {
130
133
break
131
134
}
132
- quality -= 5
133
- if quality <= 0 {
134
- return nil , fmt .Errorf ("can not to compress image to %d MB" , maxSizeMB )
135
- }
136
135
}
137
136
return buf .Bytes (), nil
138
137
}
0 commit comments