psd.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package metadata
  2. import (
  3. "errors"
  4. "image"
  5. "image/jpeg"
  6. "path/filepath"
  7. "github.com/nfnt/resize"
  8. "github.com/oliamb/cutter"
  9. _ "github.com/oov/psd"
  10. "imuslab.com/arozos/mod/filesystem"
  11. "imuslab.com/arozos/mod/utils"
  12. )
  13. func generateThumbnailForPSD(fsh *filesystem.FileSystemHandler, cacheFolder string, file string, generateOnly bool) (string, error) {
  14. if fsh.RequireBuffer {
  15. return "", nil
  16. }
  17. fshAbs := fsh.FileSystemAbstraction
  18. if !fshAbs.FileExists(file) {
  19. //The user removed this file before the thumbnail is finished
  20. return "", errors.New("Source not exists")
  21. }
  22. outputFile := cacheFolder + filepath.Base(file) + ".jpg"
  23. f, err := fshAbs.Open(file)
  24. if err != nil {
  25. return "", err
  26. }
  27. //Decode the image content with PSD decoder
  28. img, _, err := image.Decode(f)
  29. if err != nil {
  30. return "", err
  31. }
  32. f.Close()
  33. //Check boundary to decide resize mode
  34. b := img.Bounds()
  35. imgWidth := b.Max.X
  36. imgHeight := b.Max.Y
  37. var m image.Image
  38. if imgWidth > imgHeight {
  39. m = resize.Resize(0, 480, img, resize.Lanczos3)
  40. } else {
  41. m = resize.Resize(480, 0, img, resize.Lanczos3)
  42. }
  43. //Crop out the center
  44. croppedImg, err := cutter.Crop(m, cutter.Config{
  45. Width: 480,
  46. Height: 480,
  47. Mode: cutter.Centered,
  48. })
  49. outf, err := fshAbs.Create(outputFile)
  50. if err != nil {
  51. return "", err
  52. }
  53. opt := jpeg.Options{
  54. Quality: 90,
  55. }
  56. err = jpeg.Encode(outf, croppedImg, &opt)
  57. if err != nil {
  58. return "", err
  59. }
  60. outf.Close()
  61. if !generateOnly && fshAbs.FileExists(outputFile) {
  62. //return the image as well
  63. ctx, err := getImageAsBase64(fsh, outputFile)
  64. return ctx, err
  65. } else if !utils.FileExists(outputFile) {
  66. return "", errors.New("Image generation failed")
  67. }
  68. return "", nil
  69. }