Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "os"
- "path"
- "math"
- "bytes"
- "strings"
- "io/ioutil"
- "image"
- "image/color"
- "image/jpeg"
- _ "image/png"
- "github.com/gonum/plot/vg"
- "github.com/gonum/plot/vg/vgimg"
- )
- func addLabel(img image.Image, x, y int, label string) image.Image {
- bounds := img.Bounds()
- var w, h vg.Length
- w = vg.Length(bounds.Max.X) * vg.Inch / 96
- h = vg.Length(bounds.Max.Y) * vg.Inch / 96
- // imgx = vg.Length(x) * vg.Inch / 96
- // imgy = vg.Length(y) * vg.Inch / 96
- c := vgimg.New(w, h)
- rect := vg.Rectangle{}
- rect.Max.X = w
- rect.Max.Y = h
- c.DrawImage(rect, img)
- font, _ := vg.MakeFont("Courier", vg.Inch*0.7)
- c.SetColor(color.RGBA{0, 0, 0, 122})
- c.Rotate(math.Pi / 4)
- // FIXME:效率低
- for i := vg.Inch; i < vg.Inch*10000; i += vg.Inch * 100 {
- offset := i / 96
- if offset > 3*w && offset > 3*h {
- break
- }
- c.FillString(font, vg.Point{X: -2*w + offset, Y: -2*h + offset}, label)
- }
- c.Rotate(-math.Pi / 4)
- jc := vgimg.JpegCanvas{c}
- buff := new(bytes.Buffer)
- jc.WriteTo(buff)
- img, _ = jpeg.Decode(buff)
- return img
- }
- // MarkingPicture for marking picture with text
- func MarkingPicture(filepath, text string) (image.Image, error) {
- f, err := os.Open(filepath)
- if err != nil {
- return nil, err
- }
- defer f.Close()
- img, _, err := image.Decode(f)
- bounds := img.Bounds()
- img = addLabel(img, bounds.Max.X/2, bounds.Max.Y/2, text)
- if err != nil {
- return nil, err
- }
- return img, nil
- }
- func main() {
- if len(os.Args) < 3 {
- panic(fmt.Errorf("Please using like this:$ %s [file or directory] [text]", os.Args[0]))
- }
- target := os.Args[1]
- text := os.Args[2]
- if stat, err := os.Stat(target); err == nil && stat.IsDir() {
- files, _ := ioutil.ReadDir(target)
- for _, fn := range files {
- img, err := MarkingPicture(path.Join(target, fn.Name()), text)
- if err != nil {
- continue
- }
- ext := path.Ext(fn.Name())
- base := strings.Split(fn.Name(), ".")[0] + "_marked"
- f, err := os.Create(base + ext)
- if err != nil {
- panic(err)
- }
- jpeg.Encode(f, img, &jpeg.Options{Quality: 100})
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement