Golang 图片压缩可以直接使用第三方包 resize
安装
1
$ go get github.com/nfnt/resize
使用
导入
1
import "github.com/nfnt/resize"
语法
resizeResizeThumbnail
1
2
resize.Resize(width, height uint, img image.Image, interp resize.InterpolationFunction) image.Image
// resize.Resize 使用插值函数interp创建具有新尺寸(宽度,高度)的缩放图像。 如果宽度或高度设置为0,则将其设置为保留宽高比值。
1
2
resize.Thumbnail(maxWidth, maxHeight uint, img image.Image, interp resize.InterpolationFunction) image.Image
// resize.Thumbnail 缩小图像,将其纵横比保持为最大尺寸(maxWidth,maxHeight)。 如果原始尺寸小于提供的尺寸,它将返回原始图像。
简单使用
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
package main
import (
"fmt"
"github.com/nfnt/resize"
"image/png"
"os"
"log"
)
func main() {
file_path := "/Users/wxnacy/Downloads/react-app1.png"
fmt.Println("Hello World")
file, err := os.Open(file_path)
if err != nil {
log.Fatal(err)
}
// decode jpeg into image.Image
img, err := png.Decode(file)
if err != nil {
log.Fatal(err)
}
file.Close()
// resize to width 1000 using Lanczos resampling
// and preserve aspect ratio
m := resize.Resize(800, 0, img, resize.NearestNeighbor)
out, err := os.Create("react.NearestNeighbor.png")
if err != nil {
log.Fatal(err)
}
defer out.Close()
// write new image to file
png.Encode(out, m)
}
resize.InterpolationFunction
这个压缩方式的展示效果可以从这里看到 https://github.com/nfnt/resize#downsizing-samples
我挨个点连接进行,发现实在不想去纠结他们的具体原理,我只想比较压缩后的文件大小
我依次按照集中格式进行了压缩,我们对比下文件大小
1
2
3
4
5
6
7
-rw-r--r--@ 1 wxnacy staff 64633 Jan 18 18:01 react-app1.png
-rw-r--r--@ 1 wxnacy staff 19857 Jan 19 17:13 react.NearestNeighbor.png
-rw-r--r-- 1 wxnacy staff 23336 Jan 19 17:12 react.Bilinear.png
-rw-r--r-- 1 wxnacy staff 25966 Jan 19 17:12 react.MitchellNetravali.png
-rw-r--r--@ 1 wxnacy staff 27241 Jan 19 17:12 react.Lanczos2.png
-rw-r--r-- 1 wxnacy staff 27356 Jan 19 17:12 react.Bicubic.png
-rw-r--r--@ 1 wxnacy staff 31222 Jan 19 17:09 react.Lanczos3.png
Lanczos3NearestNeighbor
ok,这样我们就知道了,如果你追求清晰的或者文件大小该选什么类型了
最近更新
最近热读
扫码关注公众号,或搜索公众号“温欣爸比”
及时获取我的最新文章
