Go实战--golang实现生成缩略图服务器(disintegration/imaging、nfnt/resize)

生命不止,继续 go go go~~~~

今天做一点图片处理的东西,跟大家一起学习分享。

很久之前,介绍过golang提供的关于图片的标准库:
Go语言学习之image、image/color、image/png、image/jpeg包(the way to go)

当你search on google或百度一下的时候,你会发现很多提到了graphics-go/graphics,但是这个库不知道为何,官方好像不再提供了,很难找到了。

那也没关系,我们还有面向github编程呢!!!

温故而知新,先看一下之前的代码:
生成图片

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, 0, 0, 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

package main

import (
    "image"
    "image/color"
    "runtime"

    "github.com/disintegration/imaging"
)

func main() {
    // use all CPU cores for maximum performance
    runtime.GOMAXPROCS(runtime.NumCPU())

    // input files
    files := []string{"1.jpg", "2.jpg", "3.jpg"}

    // load images and make 100x100 thumbnails of them
    var thumbnails []image.Image
    for _, file := range files {
        img, err := imaging.Open(file)
        if err != nil {
            panic(err)
        }
        thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)
        thumbnails = append(thumbnails, thumb)
    }

    // create a new blank image
    dst := imaging.New(100*len(thumbnails), 100, color.NRGBA{0, 0, 0, 0})

    // paste thumbnails into the new image side by side
    for i, thumb := range thumbnails {
        dst = imaging.Paste(dst, thumb, image.Pt(i*100, 0))
    }

    // save the combined image to file
    err := imaging.Save(dst, "dst.jpg")
    if err != nil {
        panic(err)
    }
}

生成缩略图服务
接下来,根据用户提供的url,生成不同尺寸的缩略图。

关于golang中net/http可以参考:
Go语言学习之net/http包(The way to go)

package main

import (
    "fmt"
    "image"
    "image/color"
    "image/png"
    "net/http"
    "runtime"
    "strconv"
    "strings"

    "github.com/disintegration/imaging"
)

func main() {
    // use all CPU cores for maximum performance
    runtime.GOMAXPROCS(runtime.NumCPU())
    http.HandleFunc("/", doImageHandler)
    http.ListenAndServe("localhost:8080", nil)
}
func doImageHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("%q\n", strings.Split(r.URL.Path, "/"))
    url := strings.Split(r.URL.Path, "/")
    if len(url) != 3 {
        return
    }

    thumbnails_size := strings.Split(url[2], "_")
    if len(thumbnails_size) != 2 {
        return
    }
    thumbnails_width, _ := strconv.Atoi(thumbnails_size[0])
    thumbnails_height, _ := strconv.Atoi(thumbnails_size[1])

    img, err := imaging.Open(url[1])
    if err != nil {
        panic(err)
    }
    thumb := imaging.Thumbnail(img, thumbnails_width, thumbnails_height, imaging.CatmullRom)
    dst := imaging.New(thumbnails_width, thumbnails_height, color.NRGBA{0, 0, 0, 0})
    dst = imaging.Paste(dst, thumb, image.Pt(0, 0))

    if err != nil {
        panic(err)
    }
    header := w.Header()
    header.Add("Content-Type", "image/jpeg")

    png.Encode(w, dst)
}

例如,浏览器输入: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

等比例放大缩小图片

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, 0, 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)
}

Go实战--golang实现生成缩略图服务器(disintegration/imaging、nfnt/resize)_第1张图片

你可能感兴趣的:(go,Go从不放弃到实战)