广告平台(站长使用)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

saveFile.go 1.7 KiB

2 kuukautta sitten
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package qrcode
  2. // 生成登录二维码图片
  3. import (
  4. "errors"
  5. "image"
  6. "image/jpeg"
  7. "image/png"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "github.com/boombuler/barcode"
  12. "github.com/boombuler/barcode/qr"
  13. )
  14. func SaveJpegFile(filePath, content string, edges ...int) error {
  15. edgeLen := 300
  16. if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 {
  17. edgeLen = edges[0]
  18. }
  19. img, _ := qr.Encode(content, qr.L, qr.Unicode)
  20. img, _ = barcode.Scale(img, edgeLen, edgeLen)
  21. return writeFile(filePath, img, "jpg")
  22. }
  23. func SavePngFile(filePath, content string, edges ...int) error {
  24. edgeLen := 300
  25. if len(edges) > 0 && edges[0] > 100 && edges[0] < 2000 {
  26. edgeLen = edges[0]
  27. }
  28. img, _ := qr.Encode(content, qr.L, qr.Unicode)
  29. img, _ = barcode.Scale(img, edgeLen, edgeLen)
  30. return writeFile(filePath, img, "png")
  31. }
  32. func writeFile(filePath string, img image.Image, format string) error {
  33. if err := createDir(filePath); err != nil {
  34. return err
  35. }
  36. file, err := os.Create(filePath)
  37. defer file.Close()
  38. if err != nil {
  39. return err
  40. }
  41. switch strings.ToLower(format) {
  42. case "png":
  43. err = png.Encode(file, img)
  44. break
  45. case "jpg":
  46. err = jpeg.Encode(file, img, nil)
  47. default:
  48. return errors.New("format not accept")
  49. }
  50. if err != nil {
  51. return err
  52. }
  53. return nil
  54. }
  55. func createDir(filePath string) error {
  56. var err error
  57. // filePath, _ = filepath.Abs(filePath)
  58. dirPath := filepath.Dir(filePath)
  59. dirInfo, err := os.Stat(dirPath)
  60. if err != nil {
  61. if !os.IsExist(err) {
  62. err = os.MkdirAll(dirPath, 0777)
  63. if err != nil {
  64. return err
  65. }
  66. } else {
  67. return err
  68. }
  69. } else {
  70. if dirInfo.IsDir() {
  71. return nil
  72. }
  73. return errors.New("directory is a file")
  74. }
  75. return nil
  76. }