gif_grabber.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "fmt"
  4. "image/gif"
  5. "io"
  6. "net/http"
  7. "os"
  8. )
  9. func GrabPascoGif() error {
  10. resp, err := http.Get("https://cdn.tegna-media.com/wtsp/weather/radar/880x495/pasco30.gif")
  11. if err != nil {
  12. return fmt.Errorf("http.Get('%s') => %v", "https://cdn.tegna-media.com/wtsp/weather/radar/880x495/pasco30.gif", err)
  13. }
  14. defer resp.Body.Close()
  15. file, err := os.Create("pasco.gif")
  16. if err != nil {
  17. return fmt.Errorf("os.Create('pasco.gif') => %v", err)
  18. }
  19. defer file.Close()
  20. _, err = io.Copy(file, resp.Body)
  21. if err != nil {
  22. return fmt.Errorf("io.Copy => %v", err)
  23. }
  24. return nil
  25. }
  26. func GrabCentralFloridaGif() error {
  27. resp, err := http.Get("https://cdn.tegna-media.com/wtsp/weather/radar/880x495/central_florida.gif")
  28. if err != nil {
  29. return fmt.Errorf("http.Get('%s') => %v", "https://cdn.tegna-media.com/wtsp/weather/radar/880x495/central_florida.gif", err)
  30. }
  31. defer resp.Body.Close()
  32. file, err := os.Create("central_florida.gif")
  33. if err != nil {
  34. return fmt.Errorf("os.Create('central_florida.gif') => %v", err)
  35. }
  36. defer file.Close()
  37. _, err = io.Copy(file, resp.Body)
  38. if err != nil {
  39. return fmt.Errorf("io.Copy => %v", err)
  40. }
  41. return nil
  42. }
  43. func DecodeGif(filename string) (*gif.GIF, error) {
  44. file, err := os.Open(filename)
  45. if err != nil {
  46. return nil, fmt.Errorf("os.Open('%s') => %v", filename, err)
  47. }
  48. defer file.Close()
  49. g, err := gif.DecodeAll(file)
  50. if err != nil {
  51. return nil, fmt.Errorf("gif.DecodeAll => %v", err)
  52. }
  53. return g, nil
  54. }
  55. func EncodeGif(filename string, g *gif.GIF, separate ...bool) error {
  56. sep := false
  57. if len(separate) != 0 {
  58. sep = separate[0]
  59. }
  60. if !sep {
  61. file, err := os.Create(filename + ".gif")
  62. if err != nil {
  63. return fmt.Errorf("os.Create('%s') => %v", filename, err)
  64. }
  65. defer file.Close()
  66. err = gif.EncodeAll(file, g)
  67. if err != nil {
  68. return fmt.Errorf("gif.EncodeAll => %v", err)
  69. }
  70. return nil
  71. }
  72. for idx, frame := range g.Image {
  73. file, err := os.Create(fmt.Sprintf("%s-%d.png", filename, idx))
  74. if err != nil {
  75. return fmt.Errorf("os.Create('%s-%d.png') => %v", filename, idx, err)
  76. }
  77. defer file.Close()
  78. err = gif.Encode(file, frame, &gif.Options{
  79. NumColors: 256,
  80. })
  81. if err != nil {
  82. return fmt.Errorf("gif.Encode(%d) => %v", idx, err)
  83. }
  84. }
  85. return nil
  86. }