main.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // go-qrcode
  2. // Copyright 2014 Tom Harwood
  3. package main
  4. import (
  5. "flag"
  6. "fmt"
  7. "os"
  8. "strings"
  9. qrcode "github.com/skip2/go-qrcode"
  10. )
  11. func main() {
  12. outFile := flag.String("o", "", "out PNG file prefix, empty for stdout")
  13. size := flag.Int("s", 256, "image size (pixel)")
  14. textArt := flag.Bool("t", false, "print as text-art on stdout")
  15. negative := flag.Bool("i", false, "invert black and white")
  16. disableBorder := flag.Bool("d", false, "disable QR Code border")
  17. flag.Usage = func() {
  18. fmt.Fprintf(os.Stderr, `qrcode -- QR Code encoder in Go
  19. https://github.com/skip2/go-qrcode
  20. Flags:
  21. `)
  22. flag.PrintDefaults()
  23. fmt.Fprintf(os.Stderr, `
  24. Usage:
  25. 1. Arguments except for flags are joined by " " and used to generate QR code.
  26. Default output is STDOUT, pipe to imagemagick command "display" to display
  27. on any X server.
  28. qrcode hello word | display
  29. 2. Save to file if "display" not available:
  30. qrcode "homepage: https://github.com/skip2/go-qrcode" > out.png
  31. `)
  32. }
  33. flag.Parse()
  34. if len(flag.Args()) == 0 {
  35. flag.Usage()
  36. checkError(fmt.Errorf("Error: no content given"))
  37. }
  38. content := strings.Join(flag.Args(), " ")
  39. var err error
  40. var q *qrcode.QRCode
  41. q, err = qrcode.New(content, qrcode.Highest)
  42. checkError(err)
  43. if *disableBorder {
  44. q.DisableBorder = true
  45. }
  46. if *textArt {
  47. art := q.ToString(*negative)
  48. fmt.Println(art)
  49. return
  50. }
  51. if *negative {
  52. q.ForegroundColor, q.BackgroundColor = q.BackgroundColor, q.ForegroundColor
  53. }
  54. var png []byte
  55. png, err = q.PNG(*size)
  56. checkError(err)
  57. if *outFile == "" {
  58. os.Stdout.Write(png)
  59. } else {
  60. var fh *os.File
  61. fh, err = os.Create(*outFile + ".png")
  62. checkError(err)
  63. defer fh.Close()
  64. fh.Write(png)
  65. }
  66. }
  67. func checkError(err error) {
  68. if err != nil {
  69. fmt.Fprintf(os.Stderr, "%s\n", err)
  70. os.Exit(1)
  71. }
  72. }