GO语言实现批量压缩图片和水印
程序员文章站
2022-05-15 08:24:48
前段时间想做个图片站,就用手机照了很多相片,但是要一个个用ps去压缩修改尺寸太麻烦了。最后想到了用golang去实现,算是边学边练吧。其中用到了github.com/nfn...
前段时间想做个图片站,就用手机照了很多相片,但是要一个个用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语言有所帮助。