我需要用 ImageMagick 添加水印,出于某种原因,我需要用 golang 运行它。
这是我的代码片段
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
func main() {
currentDir, _ := os.Getwd()
sourceImg := os.Args[1]
sourceName := filepath.Base(sourceImg)
sourceExt := filepath.Ext(sourceImg)
imgNameWithoutExt := strings.Replace(sourceName, sourceExt, "", 1)
targetImgName := imgNameWithoutExt + "_wm" + sourceExt
targetImg := filepath.Join(filepath.Dir(sourceImg), targetImgName)
command := "bash"
secondParam := "-c"
// In macOS or Linux, use backslash to escape parenthesis
cmdStr := `magick "` + sourceImg + `" -set option:watermarkWidth "%[fx:int(w*0.25)]" -alpha set -background none \\( -fill "#FFFFFF80" -stroke "#FF000080" -strokeWidth 3 -undercolor "#FF000080" -font "arial.ttf" -size "%[watermarkWidth]x" label:"This is watermark" -gravity center -geometry +10+10 -rotate -30 \\) -composite -quality 40 "` + targetImg + `"`
if runtime.GOOS == "windows" {
sourceImg = strings.ReplaceAll(sourceImg, "\\", "\\\\")
targetImg = strings.ReplaceAll(targetImg, "\\", "\\\\")
// In PowerShell, use babckstick (`) to escape parenthesis
command = "cmd"
secondParam = "/c"
cmdStr = `magick "` + sourceImg + `" -set option:watermarkWidth "%[fx:int(w*0.25)]" -alpha set -background none ` + "`(" + ` -fill "#FFFFFF80" -stroke "#FF000080" -strokeWidth 3 -undercolor "#FF000080" -font "arial.ttf" -size "%[watermarkWidth]x" label:"This is watermark" -gravity center -geometry +10+10 -rotate -30 ` + "`)" + ` -composite -quality 40 "` + targetImg + `"`
}
fmt.Println(cmdStr)
cmd := exec.Command(command, secondParam, cmdStr)
cmd.Dir = currentDir
ouput, err := cmd.Output()
if err != nil {
fmt.Println("Error:", ouput, err.Error())
} else {
fmt.Println("Watermark was successfully added!")
}
}
因为我os.Getwd()在代码中使用了,所以我们不能直接运行它go run main.go,而是应该构建一个可执行文件
慕森卡
相关分类