golang修改图片尺寸
/*就简单的读取、修改、写入,应用时只需遍历目录再多开几个携程跑即可*/ package main import ( "bytes" "fmt" "image" "image/jpeg" "io/ioutil" "mylog" "os" "github.com/nfnt/resize" _ "image/gif" _ "image/png" ) func main() { old, err := os.ReadFile(`./download/png.png`) if err != nil { fmt.Println(err) } new_pic := CompressImageResource(old) ioutil.WriteFile("./download/png.jpg", new_pic, 0666) } // 默认最大高度 const MaxHeight uint = 1080 // 文件小于 200KB 或者不是jpeg/png格式,不再压缩 func CompressImageResource(data []byte) []byte { if len(data) < 1024*200 { return data } img, _, err := image.Decode(bytes.NewReader(data)) if err != nil { mylog.Printf("jpeg png compress failed,err:%v", err) return data } // 修改图片的大小 m := resize.Resize(0, MaxHeight, img, resize.Lanczos3) buf := bytes.Buffer{} // 修改图片的质量 err = jpeg.Encode(&buf, m, &jpeg.Options{Quality: 85}) if err != nil { mylog.Printf("jpeg compress failed,err:%v", err) return data } if buf.Len() > len(data) { return data } return buf.Bytes() }