You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.2 KiB

  1. package main
  2. import (
  3. "bytes"
  4. "image"
  5. "image/jpeg"
  6. "image/png"
  7. "strings"
  8. "github.com/nfnt/resize"
  9. )
  10. func dataToImage(data []byte, imageName string) (image.Image, error) {
  11. reader := bytes.NewReader(data)
  12. var imageExtension = strings.Split(imageName, ".")[1]
  13. var img image.Image
  14. var err error
  15. switch imageExtension {
  16. case "png":
  17. img, err = png.Decode(reader)
  18. case "jpg":
  19. img, err = jpeg.Decode(reader)
  20. case "jpeg":
  21. img, err = jpeg.Decode(reader)
  22. default:
  23. img = nil
  24. }
  25. if err != nil {
  26. return img, err
  27. }
  28. return img, err
  29. }
  30. func imageToData(img image.Image, imageName string) ([]byte, error) {
  31. buf := new(bytes.Buffer)
  32. var imageExtension = strings.Split(imageName, ".")[1]
  33. var err error
  34. switch imageExtension {
  35. case "png":
  36. err = png.Encode(buf, img)
  37. case "jpg":
  38. err = jpeg.Encode(buf, img, nil)
  39. case "jpeg":
  40. err = jpeg.Encode(buf, img, nil)
  41. default:
  42. img = nil
  43. }
  44. if err != nil {
  45. return buf.Bytes(), err
  46. }
  47. return buf.Bytes(), err
  48. }
  49. func imageToPNG(img image.Image) ([]byte, error) {
  50. buf := new(bytes.Buffer)
  51. var err error
  52. err = png.Encode(buf, img)
  53. return buf.Bytes(), err
  54. }
  55. func Resize(img image.Image) image.Image {
  56. r := resize.Resize(160, 0, img, resize.Lanczos3)
  57. return r
  58. }