Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. "path"
  7. "math"
  8. "bytes"
  9. "strings"
  10. "io/ioutil"
  11.  
  12. "image"
  13. "image/color"
  14. "image/jpeg"
  15. _ "image/png"
  16.  
  17. "github.com/gonum/plot/vg"
  18. "github.com/gonum/plot/vg/vgimg"
  19. )
  20.  
  21. func addLabel(img image.Image, x, y int, label string) image.Image {
  22. bounds := img.Bounds()
  23. var w, h vg.Length
  24. w = vg.Length(bounds.Max.X) * vg.Inch / 96
  25. h = vg.Length(bounds.Max.Y) * vg.Inch / 96
  26. // imgx = vg.Length(x) * vg.Inch / 96
  27. // imgy = vg.Length(y) * vg.Inch / 96
  28. c := vgimg.New(w, h)
  29. rect := vg.Rectangle{}
  30. rect.Max.X = w
  31. rect.Max.Y = h
  32. c.DrawImage(rect, img)
  33. font, _ := vg.MakeFont("Courier", vg.Inch*0.7)
  34. c.SetColor(color.RGBA{0, 0, 0, 122})
  35. c.Rotate(math.Pi / 4)
  36. // FIXME:效率低
  37. for i := vg.Inch; i < vg.Inch*10000; i += vg.Inch * 100 {
  38. offset := i / 96
  39. if offset > 3*w && offset > 3*h {
  40. break
  41. }
  42. c.FillString(font, vg.Point{X: -2*w + offset, Y: -2*h + offset}, label)
  43. }
  44. c.Rotate(-math.Pi / 4)
  45. jc := vgimg.JpegCanvas{c}
  46. buff := new(bytes.Buffer)
  47. jc.WriteTo(buff)
  48. img, _ = jpeg.Decode(buff)
  49. return img
  50. }
  51.  
  52. // MarkingPicture for marking picture with text
  53. func MarkingPicture(filepath, text string) (image.Image, error) {
  54. f, err := os.Open(filepath)
  55. if err != nil {
  56. return nil, err
  57. }
  58. defer f.Close()
  59. img, _, err := image.Decode(f)
  60. bounds := img.Bounds()
  61. img = addLabel(img, bounds.Max.X/2, bounds.Max.Y/2, text)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return img, nil
  66. }
  67.  
  68. func main() {
  69. if len(os.Args) < 3 {
  70. panic(fmt.Errorf("Please using like this:$ %s [file or directory] [text]", os.Args[0]))
  71. }
  72.  
  73. target := os.Args[1]
  74. text := os.Args[2]
  75.  
  76. if stat, err := os.Stat(target); err == nil && stat.IsDir() {
  77. files, _ := ioutil.ReadDir(target)
  78. for _, fn := range files {
  79. img, err := MarkingPicture(path.Join(target, fn.Name()), text)
  80. if err != nil {
  81. continue
  82. }
  83. ext := path.Ext(fn.Name())
  84. base := strings.Split(fn.Name(), ".")[0] + "_marked"
  85. f, err := os.Create(base + ext)
  86. if err != nil {
  87. panic(err)
  88. }
  89. jpeg.Encode(f, img, &jpeg.Options{Quality: 100})
  90. }
  91. }
  92.  
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement