生命不止,继续 go go go~~~~
很久之前,介绍过golang提供的关于图片的标准库:
Go语言学习之image、image/color、image/png、image/jpeg包(the way to go)
当你search on google或百度一下的时候,你会发现很多提到了graphics-go/graphics,但是这个库不知道为何,官方好像不再提供了,很难找到了。
那也没关系,我们还有面向github编程呢!!!
@H_404_17@package main import "image" import "image/color" import "image/png" import "os" func main() { // Create an 100 x 50 image img := image.NewRGBA(image.Rect(0, 0, 100, 50)) // Draw a red dot at (2,3) img.Set(2, 3,color.RGBA{255, 255}) // Save to out.png f,_ := os.OpenFile("out.png",os.O_WRONLY|os.O_CREATE, 0600) defer f.Close() png.Encode(f,img) }disintegration/imaging
github地址:
https://github.com/disintegration/imaging
Star: 1284
获取:
go get -u github.com/disintegration/imaging
生成缩略图
下面的代码,将三张图片生成一张缩略图。
出自:
https://www.socketloop.com/tutorials/golang-generate-thumbnails-from-images
生成缩略图服务
接下来,根据用户提供的url,生成不同尺寸的缩略图。
关于golang中net/http可以参考:
Go语言学习之net/http包(The way to go)
例如,浏览器输入:http://localhost:8080/1.jpg/80_90
就会生成一张80*90的1.jpg的缩略图
nfnt/resize
github地址:
https://github.com/nfnt/resize
Star: 1544
获取:
go get github.com/nfnt/resize
等比例放大缩小图片
@H_404_17@package main import ( "image/jpeg" "log" "os" "github.com/nfnt/resize" ) func main() { file,err := os.Open("1.jpg") if err != nil { log.Fatal(err) } img,err := jpeg.Decode(file) if err != nil { log.Fatal(err) } file.Close() // resize to width 1000 using Lanczos resampling // and preserve aspect ratio m := resize.Resize(100,img,resize.Lanczos3) out,err := os.Create("test_resized.jpg") if err != nil { log.Fatal(err) } defer out.Close() // write new image to file jpeg.Encode(out,m,nil) }