convert.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /* imageToCSSData creates a css file with embedded base64 data from a list of files
  2. $ imageToCSSData my.css Courious_cat.jpg
  3. $ cat my.css
  4. .ipfs-Curious_cat {
  5. background-image: url('data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAA...snip==');
  6. background-repeat: no-repeat;
  7. background-size: contain;
  8. }
  9. */
  10. package main
  11. import (
  12. "encoding/base64"
  13. "fmt"
  14. "io/ioutil"
  15. "log"
  16. "net/http"
  17. "os"
  18. "path/filepath"
  19. "strings"
  20. "sync"
  21. "text/template"
  22. )
  23. var cssTpl = template.Must(template.New("css").Parse(`
  24. .ipfs-{{.Name}} {
  25. background-image: url('data:{{.Mime}};base64,{{.Data}}');
  26. background-repeat: no-repeat;
  27. background-size: contain;
  28. }
  29. `))
  30. func main() {
  31. if len(os.Args) != 3 {
  32. fmt.Println("usage: convert [fname.css] [glob of files]")
  33. os.Exit(1)
  34. }
  35. css, err := os.Create(os.Args[1])
  36. check(err)
  37. files, err := filepath.Glob(os.Args[2])
  38. check(err)
  39. var wg sync.WaitGroup
  40. for _, f := range files {
  41. wg.Add(1)
  42. go func(fname string) {
  43. defer wg.Done()
  44. raw, err := ioutil.ReadFile(fname)
  45. check(err)
  46. shortName := filepath.Base(fname)
  47. shortName = strings.Split(shortName, ".")[0]
  48. mtype := http.DetectContentType(raw)
  49. b64 := base64.StdEncoding.EncodeToString(raw)
  50. err = cssTpl.Execute(css, struct {
  51. Name string
  52. Mime string
  53. Data string
  54. }{shortName, mtype, b64})
  55. check(err)
  56. fmt.Println(fname, ": converted")
  57. }(f)
  58. }
  59. wg.Wait()
  60. check(css.Close())
  61. log.Println("all done")
  62. }
  63. func check(err error) {
  64. if err != nil {
  65. log.Fatal(err)
  66. }
  67. }