├── .editorconfig ├── .github └── workflows │ ├── codeql-analysis.yml │ └── go.yml ├── .gitignore ├── LICENSE ├── README.md ├── bench_test.go ├── go.mod ├── go.sum ├── testdata ├── background.gif ├── background.jpg ├── background.png ├── background.unsupported ├── output │ └── .gitkeep ├── watermark.gif ├── watermark.jpg ├── watermark.png └── watermark.unsupported ├── watermark.go └── watermark_test.go /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: http://EditorConfig.org 2 | 3 | # top-most EditorConfig file 4 | root = true 5 | 6 | # Unix-style newlines with a newline ending every file 7 | [*] 8 | end_of_line = lf 9 | insert_final_newline = true 10 | charset = utf-8 11 | 12 | # html 13 | [*.{htm,html,js,css}] 14 | indent_style = space 15 | indent_size = 4 16 | 17 | # 配置文件 18 | [*.{yml,yaml,json}] 19 | indent_style = space 20 | indent_size = 2 21 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 8 * * 0' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['go'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | 35 | # Initializes the CodeQL tools for scanning. 36 | - name: Initialize CodeQL 37 | uses: github/codeql-action/init@v2 38 | with: 39 | languages: ${{ matrix.language }} 40 | # If you wish to specify custom queries, you can do so here or in a config file. 41 | # By default, queries listed here will override any specified in a config file. 42 | # Prefix the list here with "+" to use these queries and those in the config file. 43 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 44 | 45 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 46 | # If this step fails, then you should remove it and run the build manually (see below) 47 | - name: Autobuild 48 | uses: github/codeql-action/autobuild@v2 49 | 50 | # ℹ️ Command-line programs to run using the OS shell. 51 | # 📚 https://git.io/JvXDl 52 | 53 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 54 | # and modify them (or add more) to build your code if your project 55 | # uses a compiled language 56 | 57 | #- run: | 58 | # make bootstrap 59 | # make release 60 | 61 | - name: Perform CodeQL Analysis 62 | uses: github/codeql-action/analyze@v2 63 | -------------------------------------------------------------------------------- /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | name: Go 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | name: Test 7 | runs-on: ${{ matrix.os }} 8 | 9 | strategy: 10 | matrix: 11 | os: [ubuntu-latest, macOS-latest, windows-latest] 12 | go: ["1.21.x", "1.24.x"] 13 | 14 | steps: 15 | - name: Check out code into the Go module directory 16 | uses: actions/checkout@v4 17 | 18 | - name: Set up Go ${{ matrix.go }} 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: ${{ matrix.go }} 22 | id: go 23 | 24 | - name: Vet 25 | run: go vet -v ./... 26 | 27 | - name: Test 28 | run: go test -race -v -coverprofile='coverage.txt' -covermode=atomic ./... 29 | 30 | - name: Upload Coverage report 31 | uses: codecov/codecov-action@v5 32 | with: 33 | token: ${{secrets.CODECOV_TOKEN}} 34 | files: ./coverage.txt 35 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | /testdata/output/* 14 | !/testdata/output/.gitkeep 15 | 16 | *.swp 17 | .DS_Store 18 | .idea/ 19 | .vscode/ 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 caixw 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | watermark 2 | [![Go](https://github.com/issue9/watermark/workflows/Go/badge.svg)](https://github.com/issue9/watermark/actions?query=workflow%3AGo) 3 | [![codecov](https://codecov.io/gh/issue9/watermark/branch/master/graph/badge.svg)](https://codecov.io/gh/issue9/watermark) 4 | [![license](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat)](https://opensource.org/licenses/MIT) 5 | [![PkgGoDev](https://pkg.go.dev/badge/github.com/issue9/watermark)](https://pkg.go.dev/github.com/issue9/watermark) 6 | ====== 7 | 8 | watermark 提供了简单的图片水印处理功能。支持处理 GIF、PNG 和 JPEG,水印也只支持这些类型的文件。 9 | 10 | 对于 GIF 水印,若被渲染图片为非 GIF 图片,则只取水印的第一帧作为水印内容; 11 | 若被渲染图片也是 GIF,则会将被渲染图片的第一帧与水印的第一帧合并, 12 | 水印的第二帧与被渲染图片的第二帧合并,依次类推。水印帧数不够的,则循环使用, 13 | 直到被渲染图片的帧数用完。 14 | 15 | ```go 16 | w, err := watermark.New("./path/to/watermark/file", 2, watermark.Center) 17 | if err != nil{ 18 | panic(err) 19 | } 20 | 21 | err = w.MarkFile("./path/to/file") 22 | ``` 23 | 24 | 安装 25 | ---- 26 | 27 | ```shell 28 | go get github.com/issue9/watermark 29 | ``` 30 | 31 | 版权 32 | ---- 33 | 34 | 本项目采用 [MIT](https://opensource.org/licenses/MIT) 开源授权许可证,完整的授权说明可在 [LICENSE](LICENSE) 文件中找到。 35 | -------------------------------------------------------------------------------- /bench_test.go: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2018-2024 caixw 2 | // 3 | // SPDX-License-Identifier: MIT 4 | 5 | package watermark 6 | 7 | import ( 8 | "os" 9 | "testing" 10 | 11 | "github.com/issue9/assert/v4" 12 | ) 13 | 14 | func BenchmarkWater_MakeImage_500xJPEG(b *testing.B) { 15 | a := assert.New(b, false) 16 | 17 | copyBackgroundFile(a, "./testdata/output/bench.jpg", "./testdata/background.jpg") 18 | 19 | w, err := NewFromFile("./testdata/watermark.jpg", 10, TopLeft) 20 | a.NotError(err).NotNil(w) 21 | 22 | file, err := os.OpenFile("./testdata/output/bench.jpg", os.O_RDWR, os.ModePerm) 23 | a.NotError(err).NotNil(file) 24 | defer file.Close() 25 | 26 | for i := 0; i < b.N; i++ { 27 | w.Mark(file, ".jpg") 28 | } 29 | } 30 | 31 | func BenchmarkWater_MakeImage_500xPNG(b *testing.B) { 32 | a := assert.New(b, false) 33 | 34 | copyBackgroundFile(a, "./testdata/output/bench.png", "./testdata/background.png") 35 | 36 | w, err := NewFromFile("./testdata/watermark.png", 10, TopLeft) 37 | a.NotError(err).NotNil(w) 38 | 39 | file, err := os.OpenFile("./testdata/output/bench.png", os.O_RDWR, os.ModePerm) 40 | a.NotError(err).NotNil(file) 41 | defer file.Close() 42 | 43 | for i := 0; i < b.N; i++ { 44 | w.Mark(file, ".png") 45 | } 46 | } 47 | 48 | func BenchmarkWater_MakeImage_500xGIF(b *testing.B) { 49 | a := assert.New(b, false) 50 | 51 | copyBackgroundFile(a, "./testdata/output/bench.gif", "./testdata/background.gif") 52 | 53 | w, err := NewFromFile("./testdata/watermark.gif", 10, TopLeft) 54 | a.NotError(err).NotNil(w) 55 | 56 | file, err := os.OpenFile("./testdata/output/bench.gif", os.O_RDWR, os.ModePerm) 57 | a.NotError(err).NotNil(file) 58 | defer file.Close() 59 | 60 | for i := 0; i < b.N; i++ { 61 | w.Mark(file, ".gif") 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/issue9/watermark 2 | 3 | go 1.21 4 | 5 | require github.com/issue9/assert/v4 v4.3.1 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/issue9/assert/v4 v4.3.1 h1:dHYODk1yV7j/1baIB6K6UggI4r1Hfuljqic7PaDbwLg= 2 | github.com/issue9/assert/v4 v4.3.1/go.mod h1:v7qDRXi7AsaZZNh8eAK2rkLJg5/clztqQGA1DRv9Lv4= 3 | -------------------------------------------------------------------------------- /testdata/background.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/background.gif -------------------------------------------------------------------------------- /testdata/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/background.jpg -------------------------------------------------------------------------------- /testdata/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/background.png -------------------------------------------------------------------------------- /testdata/background.unsupported: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/background.unsupported -------------------------------------------------------------------------------- /testdata/output/.gitkeep: -------------------------------------------------------------------------------- 1 | *.* 2 | -------------------------------------------------------------------------------- /testdata/watermark.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/watermark.gif -------------------------------------------------------------------------------- /testdata/watermark.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/watermark.jpg -------------------------------------------------------------------------------- /testdata/watermark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/watermark.png -------------------------------------------------------------------------------- /testdata/watermark.unsupported: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/issue9/watermark/175e67a4e4cfd7c7ee9cdfedfe3a2126e2ecfd8c/testdata/watermark.unsupported -------------------------------------------------------------------------------- /watermark.go: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2018-2024 caixw 2 | // 3 | // SPDX-License-Identifier: MIT 4 | 5 | // Package watermark 提供一个简单的水印功能 6 | package watermark 7 | 8 | import ( 9 | "errors" 10 | "image" 11 | "image/draw" 12 | "image/gif" 13 | "image/jpeg" 14 | "image/png" 15 | "io" 16 | "io/fs" 17 | "os" 18 | "path/filepath" 19 | "slices" 20 | "strings" 21 | ) 22 | 23 | // 水印的位置 24 | const ( 25 | TopLeft Pos = iota 26 | TopRight 27 | BottomLeft 28 | BottomRight 29 | Center 30 | ) 31 | 32 | var ( 33 | // ErrUnsupportedWatermarkType 不支持的水印类型 34 | ErrUnsupportedWatermarkType = errors.New("不支持的水印类型") 35 | 36 | // ErrWatermarkTooLarge 当水印位置距离右下角的范围小于水印图片时,返回错误。 37 | ErrWatermarkTooLarge = errors.New("水印太大") 38 | ) 39 | 40 | // 允许做水印的图片类型 41 | var allowExts = []string{ 42 | ".gif", ".jpg", ".jpeg", ".png", 43 | } 44 | 45 | // Pos 表示水印的位置 46 | type Pos int 47 | 48 | // Watermark 用于给图片添加水印功能 49 | // 50 | // 目前支持 gif、jpeg 和 png 三种图片格式。 51 | // 若是 gif 图片,则只取图片的第一帧;png 支持透明背景。 52 | type Watermark struct { 53 | image image.Image // 水印图片 54 | gifImg *gif.GIF // 如果是 GIF 图片,image 保存第一帧的图片, gifImg 保存全部内容 55 | padding int // 水印留的边白 56 | pos Pos // 水印的位置 57 | } 58 | 59 | // AllowExts 当前包支持的所有文件类型 60 | func AllowExts() []string { return slices.Clone(allowExts) } 61 | 62 | // NewFromFile 从文件声明一个 [Watermark] 对象 63 | // 64 | // path 为水印文件的路径; 65 | // padding 为水印在目标图像上的留白大小; 66 | // pos 水印的位置。 67 | func NewFromFile(path string, padding int, pos Pos) (*Watermark, error) { 68 | f, err := os.Open(path) 69 | if err != nil { 70 | return nil, err 71 | } 72 | defer f.Close() 73 | 74 | return New(f, filepath.Ext(path), padding, pos) 75 | } 76 | 77 | // NewFromFS 从文件系统初始化 [Watermark] 对象 78 | func NewFromFS(fsys fs.FS, path string, padding int, pos Pos) (*Watermark, error) { 79 | f, err := fsys.Open(path) 80 | if err != nil { 81 | return nil, err 82 | } 83 | defer f.Close() 84 | 85 | return New(f, filepath.Ext(path), padding, pos) 86 | } 87 | 88 | // New 声明 [Watermark] 对象 89 | // 90 | // r 为水印图片内容; 91 | // ext 为水印图片的扩展名,会根据扩展名判断图片类型; 92 | // padding 为水印在目标图像上的留白大小; 93 | // pos 图片位置; 94 | func New(r io.Reader, ext string, padding int, pos Pos) (w *Watermark, err error) { 95 | if pos < TopLeft || pos > Center { 96 | panic("无效的 pos 值") 97 | } 98 | 99 | var img image.Image 100 | var gifImg *gif.GIF 101 | switch strings.ToLower(ext) { 102 | case ".jpg", ".jpeg": 103 | img, err = jpeg.Decode(r) 104 | case ".png": 105 | img, err = png.Decode(r) 106 | case ".gif": 107 | gifImg, err = gif.DecodeAll(r) 108 | img = gifImg.Image[0] 109 | default: 110 | return nil, ErrUnsupportedWatermarkType 111 | } 112 | if err != nil { 113 | return nil, err 114 | } 115 | 116 | return &Watermark{ 117 | image: img, 118 | gifImg: gifImg, 119 | padding: padding, 120 | pos: pos, 121 | }, nil 122 | } 123 | 124 | // IsAllowExt 该扩展名的图片是否允许使用水印 125 | // 126 | // ext 必须带上 . 符号 127 | func IsAllowExt(ext string) bool { 128 | if ext == "" { 129 | panic("参数 ext 不能为空") 130 | } 131 | 132 | if ext[0] != '.' { 133 | panic("参数 ext 必须以 . 开头") 134 | } 135 | 136 | ext = strings.ToLower(ext) 137 | 138 | for _, e := range allowExts { 139 | if e == ext { 140 | return true 141 | } 142 | } 143 | return false 144 | } 145 | 146 | // MarkFile 给指定的文件打上水印 147 | func (w *Watermark) MarkFile(path string) error { 148 | file, err := os.OpenFile(path, os.O_RDWR, os.ModePerm) 149 | if err != nil { 150 | return err 151 | } 152 | defer file.Close() 153 | 154 | return w.Mark(file, strings.ToLower(filepath.Ext(path))) 155 | } 156 | 157 | // Mark 将水印写入 src 中,由 ext 确定当前图片的类型。 158 | func (w *Watermark) Mark(src io.ReadWriteSeeker, ext string) (err error) { 159 | var srcImg image.Image 160 | 161 | ext = strings.ToLower(ext) 162 | switch ext { 163 | case ".gif": 164 | return w.markGIF(src) // GIF 另外单独处理 165 | case ".jpg", ".jpeg": 166 | srcImg, err = jpeg.Decode(src) 167 | case ".png": 168 | srcImg, err = png.Decode(src) 169 | default: 170 | return ErrUnsupportedWatermarkType 171 | } 172 | if err != nil { 173 | return err 174 | } 175 | 176 | bound := srcImg.Bounds() 177 | point := w.getPoint(bound.Dx(), bound.Dy()) 178 | 179 | if err = w.checkTooLarge(point, bound); err != nil { 180 | return err 181 | } 182 | 183 | dstImg := image.NewNRGBA64(srcImg.Bounds()) 184 | draw.Draw(dstImg, dstImg.Bounds(), srcImg, image.Point{}, draw.Src) 185 | draw.Draw(dstImg, dstImg.Bounds(), w.image, point, draw.Over) 186 | 187 | if _, err = src.Seek(0, 0); err != nil { 188 | return err 189 | } 190 | 191 | switch ext { 192 | case ".jpg", ".jpeg": 193 | return jpeg.Encode(src, dstImg, nil) 194 | case ".png": 195 | return png.Encode(src, dstImg) 196 | default: 197 | return ErrUnsupportedWatermarkType 198 | } 199 | } 200 | 201 | func (w *Watermark) markGIF(src io.ReadWriteSeeker) error { 202 | srcGIF, err := gif.DecodeAll(src) 203 | if err != nil { 204 | return err 205 | } 206 | bound := srcGIF.Image[0].Bounds() 207 | point := w.getPoint(bound.Dx(), bound.Dy()) 208 | 209 | if err = w.checkTooLarge(point, bound); err != nil { 210 | return err 211 | } 212 | 213 | if w.gifImg == nil { 214 | for index, img := range srcGIF.Image { 215 | dstImg := image.NewPaletted(img.Bounds(), img.Palette) 216 | draw.Draw(dstImg, dstImg.Bounds(), img, image.Point{}, draw.Src) 217 | draw.Draw(dstImg, dstImg.Bounds(), w.image, point, draw.Over) 218 | srcGIF.Image[index] = dstImg 219 | } 220 | } else { // 水印也是 GIF 221 | windex := 0 222 | wmax := len(w.gifImg.Image) 223 | for index, img := range srcGIF.Image { 224 | dstImg := image.NewPaletted(img.Bounds(), img.Palette) 225 | draw.Draw(dstImg, dstImg.Bounds(), img, image.Point{}, draw.Src) 226 | 227 | // 获取对应帧数的水印图片 228 | if windex >= wmax { 229 | windex = 0 230 | } 231 | draw.Draw(dstImg, dstImg.Bounds(), w.gifImg.Image[windex], point, draw.Over) 232 | windex++ 233 | 234 | srcGIF.Image[index] = dstImg 235 | } 236 | } 237 | 238 | if _, err = src.Seek(0, 0); err != nil { 239 | return err 240 | } 241 | return gif.EncodeAll(src, srcGIF) 242 | } 243 | 244 | func (w *Watermark) checkTooLarge(start image.Point, dst image.Rectangle) error { 245 | // 允许的最大高宽 246 | width := dst.Dx() - start.X - w.padding 247 | height := dst.Dy() - start.Y - w.padding 248 | 249 | if width < w.image.Bounds().Dx() || height < w.image.Bounds().Dy() { 250 | return ErrWatermarkTooLarge 251 | } 252 | return nil 253 | } 254 | 255 | func (w *Watermark) getPoint(width, height int) image.Point { 256 | var point image.Point 257 | 258 | switch w.pos { 259 | case TopLeft: 260 | point = image.Point{X: -w.padding, Y: -w.padding} 261 | case TopRight: 262 | point = image.Point{ 263 | X: -(width - w.padding - w.image.Bounds().Dx()), 264 | Y: -w.padding, 265 | } 266 | case BottomLeft: 267 | point = image.Point{ 268 | X: -w.padding, 269 | Y: -(height - w.padding - w.image.Bounds().Dy()), 270 | } 271 | case BottomRight: 272 | point = image.Point{ 273 | X: -(width - w.padding - w.image.Bounds().Dx()), 274 | Y: -(height - w.padding - w.image.Bounds().Dy()), 275 | } 276 | case Center: 277 | point = image.Point{ 278 | X: -(width - w.padding - w.image.Bounds().Dx()) / 2, 279 | Y: -(height - w.padding - w.image.Bounds().Dy()) / 2, 280 | } 281 | default: 282 | panic("无效的 pos 值") 283 | } 284 | 285 | return point 286 | } 287 | -------------------------------------------------------------------------------- /watermark_test.go: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2018-2024 caixw 2 | // 3 | // SPDX-License-Identifier: MIT 4 | 5 | package watermark 6 | 7 | import ( 8 | "image" 9 | "io" 10 | "os" 11 | "testing" 12 | 13 | "github.com/issue9/assert/v4" 14 | ) 15 | 16 | // 复制文件到 output 目录下,并重命名。 17 | func copyBackgroundFile(a *assert.Assertion, dest, src string) { 18 | destFile, err := os.Create(dest) 19 | a.NotError(err).NotNil(destFile) 20 | 21 | srcFile, err := os.Open(src) 22 | a.NotError(err).NotNil(srcFile) 23 | 24 | n, err := io.Copy(destFile, srcFile) 25 | a.NotError(err).True(n >= 0) 26 | 27 | destFile.Close() 28 | srcFile.Close() 29 | } 30 | 31 | // 输出各种组合的水印图片。 32 | // bgExt 表示背景图片的扩展名。 33 | // water 表示水印图片的扩展名。 34 | func output(a *assert.Assertion, pos Pos, bgExt, waterExt string) { 35 | water := "./testdata/watermark" + waterExt 36 | src := "./testdata/background" + bgExt 37 | dest := "./testdata/output/" + waterExt[1:] + bgExt 38 | 39 | copyBackgroundFile(a, dest, src) 40 | 41 | // 添加水印 42 | w, err := NewFromFile(water, 10, pos) 43 | a.NotError(err).NotNil(w) 44 | a.NotError(w.MarkFile(dest)) 45 | } 46 | 47 | func TestNewFromFile(t *testing.T) { 48 | a := assert.New(t, false) 49 | 50 | w, err := NewFromFile("./testdata/watermark.unsupported", 10, TopLeft) 51 | a.Equal(err, ErrUnsupportedWatermarkType).Nil(w) 52 | 53 | a.Panic(func() { 54 | w, err = NewFromFile("./testdata/watermark.png", 10, -1) 55 | }) 56 | 57 | src := "./testdata/background.unsupported" 58 | dest := "./testdata/output/unsupported.unsupported" 59 | copyBackgroundFile(a, dest, src) 60 | 61 | w, err = NewFromFile("./testdata/watermark.png", 10, TopLeft) 62 | a.NotError(err).NotNil(w) 63 | err = w.MarkFile(dest) 64 | a.Equal(err, ErrUnsupportedWatermarkType) 65 | } 66 | 67 | func TestWatermark_MarkFile(t *testing.T) { 68 | a := assert.New(t, false) 69 | 70 | output(a, TopLeft, ".jpg", ".jpg") 71 | output(a, TopRight, ".jpg", ".png") 72 | output(a, Center, ".jpg", ".gif") 73 | 74 | output(a, BottomLeft, ".png", ".jpg") 75 | output(a, BottomRight, ".png", ".png") 76 | output(a, Center, ".png", ".gif") 77 | 78 | output(a, BottomLeft, ".gif", ".jpg") 79 | output(a, BottomRight, ".gif", ".png") 80 | output(a, Center, ".gif", ".gif") 81 | } 82 | 83 | func TestIsAllowExt(t *testing.T) { 84 | a := assert.New(t, false) 85 | 86 | a.True(IsAllowExt(".jpg")) 87 | a.True(IsAllowExt(".JPeG")) 88 | a.True(IsAllowExt(".png")) 89 | a.True(IsAllowExt(".Gif")) 90 | 91 | a.Panic(func() { IsAllowExt("") }) 92 | a.Panic(func() { IsAllowExt("gif") }) 93 | } 94 | 95 | func TestWater_checkTooLarge(t *testing.T) { 96 | a := assert.New(t, false) 97 | 98 | w, err := NewFromFile("./testdata/watermark.png", 10, BottomRight) 99 | a.NotError(err).NotNil(w) 100 | dst := image.Rect(0, 0, w.image.Bounds().Dx(), w.image.Bounds().Dy()) 101 | a.Equal(w.checkTooLarge(image.Point{X: 0, Y: 0}, dst), ErrWatermarkTooLarge) 102 | 103 | // padding 为 0 正好 1:1 覆盖 104 | w.padding = 0 105 | dst = image.Rect(0, 0, w.image.Bounds().Dx(), w.image.Bounds().Dy()) 106 | a.NotError(w.checkTooLarge(image.Point{X: 0, Y: 0}, dst)) 107 | } 108 | --------------------------------------------------------------------------------