我需要用 ImageMagick 添加水印,出于某種原因,我需要用 golang 運(yùn)行它。這是我的代碼片段package mainimport ( "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!") }}因?yàn)槲襬s.Getwd()在代碼中使用了,所以我們不能直接運(yùn)行它go run main.go,而是應(yīng)該構(gòu)建一個(gè)可執(zhí)行文件
1 回答

慕森卡
TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超8個(gè)贊
您沒有使用PowerShell從您的 Go 應(yīng)用程序內(nèi)部調(diào)用您的可執(zhí)行文件,您正在使用cmd.exe
,它具有不同的語法規(guī)則(它不識(shí)別`
(反引號(hào))作為轉(zhuǎn)義字符,%
是一個(gè)元字符,不支持轉(zhuǎn)義"
為\"
, ...)
因此,由于您錯(cuò)誤地將專為powershell.exe
(Windows PowerShell CLI)設(shè)計(jì)的命令行傳遞給cmd.exe
舊版 Windows shell,由于語法差異,它失敗了。
因此,替換:
command = "cmd" secondParam = "/c"
和:
command = "powershell.exe" secondParam = "-c"
此外,考慮在 之前放置以下參數(shù)-c
,以增加穩(wěn)健性:
"-ExecutionPolicy", "Bypass", "-NoProfile"
請(qǐng)參閱文檔powershell.exe
。
退一步說:
您的可執(zhí)行調(diào)用不使用任何shell 功能(例如重定向到文件、通過管道連接多個(gè)命令,...),因此您可以直接調(diào)用,將其及其所有參數(shù)單獨(dú)magick
傳遞給exec.Command()
,從而加快速度操作并避免轉(zhuǎn)義的需要。
- 1 回答
- 0 關(guān)注
- 131 瀏覽
添加回答
舉報(bào)
0/150
提交
取消