audio.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package metadata
  2. import (
  3. "bytes"
  4. "image"
  5. "image/jpeg"
  6. "path/filepath"
  7. "github.com/dhowden/tag"
  8. "github.com/nfnt/resize"
  9. "github.com/oliamb/cutter"
  10. "imuslab.com/arozos/mod/filesystem"
  11. )
  12. func generateThumbnailForAudio(fsh *filesystem.FileSystemHandler, cacheFolder string, file string, generateOnly bool) (string, error) {
  13. if fsh.RequireBuffer {
  14. return "", nil
  15. }
  16. fshAbs := fsh.FileSystemAbstraction
  17. //This extension is supported by id4. Call to library
  18. f, err := fshAbs.Open(file)
  19. if err != nil {
  20. return "", err
  21. }
  22. defer f.Close()
  23. m, err := tag.ReadFrom(f)
  24. if err != nil {
  25. return "", err
  26. }
  27. if m.Picture() != nil {
  28. //Convert the picture bytecode to image object
  29. img, _, err := image.Decode(bytes.NewReader(m.Picture().Data))
  30. if err != nil {
  31. //Fail to convert this image. Continue next one
  32. return "", err
  33. }
  34. //Create an empty file
  35. out, _ := fshAbs.Create(cacheFolder + filepath.Base(file) + ".jpg")
  36. defer out.Close()
  37. b := img.Bounds()
  38. imgWidth := b.Max.X
  39. imgHeight := b.Max.Y
  40. //Resize the albumn image
  41. var m image.Image
  42. if imgWidth > imgHeight {
  43. m = resize.Resize(0, 480, img, resize.Lanczos3)
  44. } else {
  45. m = resize.Resize(480, 0, img, resize.Lanczos3)
  46. }
  47. //Crop out the center
  48. croppedImg, _ := cutter.Crop(m, cutter.Config{
  49. Width: 480,
  50. Height: 480,
  51. Mode: cutter.Centered,
  52. })
  53. //Write the cache image to disk
  54. jpeg.Encode(out, croppedImg, nil)
  55. if !generateOnly {
  56. //return the image as well
  57. ctx, err := getImageAsBase64(fsh, cacheFolder+filepath.Base(file)+".jpg")
  58. return ctx, err
  59. }
  60. }
  61. return "", nil
  62. }