audio.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, err := fshAbs.Create(cacheFolder + filepath.Base(file) + ".jpg")
  36. if err != nil {
  37. return "", err
  38. }
  39. defer out.Close()
  40. b := img.Bounds()
  41. imgWidth := b.Max.X
  42. imgHeight := b.Max.Y
  43. //Resize the albumn image
  44. var m image.Image
  45. if imgWidth > imgHeight {
  46. m = resize.Resize(0, 480, img, resize.Lanczos3)
  47. } else {
  48. m = resize.Resize(480, 0, img, resize.Lanczos3)
  49. }
  50. //Crop out the center
  51. croppedImg, _ := cutter.Crop(m, cutter.Config{
  52. Width: 480,
  53. Height: 480,
  54. Mode: cutter.Centered,
  55. })
  56. //Write the cache image to disk
  57. jpeg.Encode(out, croppedImg, nil)
  58. if !generateOnly {
  59. //return the image as well
  60. ctx, err := getImageAsBase64(fsh, cacheFolder+filepath.Base(file)+".jpg")
  61. return ctx, err
  62. }
  63. }
  64. return "", nil
  65. }