psd.go 1.5 KB

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