前段時間想做個圖片站,就用手機照了很多相片,但是要一個個用PS去壓縮修改尺寸太麻煩了。最後想到了用golang去實現,算是邊學邊練吧。其中用到了github.com/nfnt/resize這個第三方庫,僅僅支援JPG圖片格式。
複製代碼 代碼如下:
package main
import (
"fmt"
"github.com/nfnt/resize"
"image"
"image/draw"
"image/jpeg"
"image/png"
"io/ioutil"
"log"
"math/rand"
"os"
"runtime"
"strconv"
"strings"
"time"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
cmd("data/")
fmt.Println("OK!")
}
// 執行操作
func cmd(path string) {
files, _ := ioutil.ReadDir(path)
for _, file := range files {
if file.IsDir() {
fmt.Println("目錄" + file.Name())
cmd(path + file.Name() + "/")
} else {
if strings.Contains(strings.ToLower(file.Name()), ".jpg") {
// 隨機名稱
to := path + random_name() + ".jpg"
origin := path + file.Name()
fmt.Println("正在處理" + origin + ">>>" + to)
cmd_resize(origin, 2048, 0, to)
defer os.Remove(origin)
}
}
}
}
// 改變大小
func cmd_resize(file string, width uint, height uint, to string) {
// 開啟圖片並解碼
file_origin, _ := os.Open(file)
origin, _ := jpeg.Decode(file_origin)
defer file_origin.Close()
canvas := resize.Resize(width, height, origin, resize.Lanczos3)
file_out, err := os.Create(to)
if err != nil {
log.Fatal(err)
}
defer file_out.Close()
jpeg.Encode(file_out, canvas, &jpeg.Options{80})
// cmd_watermark(to, strings.Replace(to, ".jpg", "@big.jpg", 1))
cmd_thumbnail(to, 480, 360, strings.Replace(to, ".jpg", "@small.jpg", 1))
}
func cmd_thumbnail(file string, width uint, height uint, to string) {
// 開啟圖片並解碼
file_origin, _ := os.Open(file)
origin, _ := jpeg.Decode(file_origin)
defer file_origin.Close()
canvas := resize.Thumbnail(width, height, origin, resize.Lanczos3)
file_out, err := os.Create(to)
if err != nil {
log.Fatal(err)
}
defer file_out.Close()
jpeg.Encode(file_out, canvas, &jpeg.Options{80})
}
// 浮水印
func cmd_watermark(file string, to string) {
// 開啟圖片並解碼
file_origin, _ := os.Open(file)
origin, _ := jpeg.Decode(file_origin)
defer file_origin.Close()
// 開啟浮水印圖並解碼
file_watermark, _ := os.Open("watermark.png")
watermark, _ := png.Decode(file_watermark)
defer file_watermark.Close()
//原始圖界限
origin_size := origin.Bounds()
//建立新圖層
canvas := image.NewNRGBA(origin_size)
// 貼原始圖
draw.Draw(canvas, origin_size, origin, image.ZP, draw.Src)
// 貼浮水印圖
draw.Draw(canvas, watermark.Bounds().Add(image.Pt(30, 30)), watermark, image.ZP, draw.Over)
//產生新圖片
create_image, _ := os.Create(to)
jpeg.Encode(create_image, canvas, &jpeg.Options{95})
defer create_image.Close()
}
// 隨機組建檔案名
func random_name() string {
rand.Seed(time.Now().UnixNano())
return strconv.Itoa(rand.Int())
}
以上就是本文所述的全部內容了,希望能夠對大家熟練掌握go語言有所協助。