audio.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package renderer
  2. import (
  3. "bytes"
  4. "errors"
  5. "image"
  6. "image/jpeg"
  7. "os"
  8. "path/filepath"
  9. "github.com/dhowden/tag"
  10. "github.com/nfnt/resize"
  11. "github.com/oliamb/cutter"
  12. )
  13. // Generate thumbnail for audio. Output file will have the same name as the input file with .jpg extension
  14. func generateThumbnailForAudio(inputFile string, outputFolder string) error {
  15. //This extension is supported by id4. Call to library
  16. f, err := os.Open(inputFile)
  17. if err != nil {
  18. return err
  19. }
  20. defer f.Close()
  21. m, err := tag.ReadFrom(f)
  22. if err != nil {
  23. return err
  24. }
  25. if m.Picture() != nil {
  26. //Convert the picture bytecode to image object
  27. img, _, err := image.Decode(bytes.NewReader(m.Picture().Data))
  28. if err != nil {
  29. //Fail to convert this image. Continue next one
  30. return err
  31. }
  32. //Create an empty file
  33. outputFilename := filepath.Join(outputFolder, filepath.Base(inputFile))
  34. out, err := os.Create(outputFilename + ".jpg")
  35. if err != nil {
  36. return err
  37. }
  38. defer out.Close()
  39. b := img.Bounds()
  40. imgWidth := b.Max.X
  41. imgHeight := b.Max.Y
  42. //Resize the albumn image
  43. var m image.Image
  44. if imgWidth > imgHeight {
  45. m = resize.Resize(0, 480, img, resize.Lanczos3)
  46. } else {
  47. m = resize.Resize(480, 0, img, resize.Lanczos3)
  48. }
  49. //Crop out the center
  50. croppedImg, _ := cutter.Crop(m, cutter.Config{
  51. Width: 480,
  52. Height: 480,
  53. Mode: cutter.Centered,
  54. })
  55. //Write the cache image to disk
  56. jpeg.Encode(out, croppedImg, nil)
  57. }
  58. return errors.New("no image found")
  59. }