resize.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/emqx/kuiper/xstream/api"
  6. "github.com/nfnt/resize"
  7. "image"
  8. "image/jpeg"
  9. "image/png"
  10. )
  11. type imageResize struct {
  12. }
  13. func (f *imageResize) Validate(args []interface{}) error {
  14. if len(args) != 3 {
  15. return fmt.Errorf("The resize function supports 3 parameters, but got %d", len(args))
  16. }
  17. return nil
  18. }
  19. func (f *imageResize) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
  20. arg, ok := args[0].([]byte)
  21. if !ok {
  22. return fmt.Errorf("arg[0] is not a bytea, got %v", args[0]), false
  23. }
  24. width, ok := args[1].(int)
  25. if !ok || 0 > width {
  26. return fmt.Errorf("arg[1] is not a bigint, got %v", args[1]), false
  27. }
  28. height, ok := args[2].(int)
  29. if !ok || 0 > height {
  30. return fmt.Errorf("arg[2] is not a bigint, got %v", args[2]), false
  31. }
  32. img, format, err := image.Decode(bytes.NewReader(arg))
  33. if nil != err {
  34. return fmt.Errorf("image decode error:%v", err), false
  35. }
  36. img = resize.Resize(uint(width), uint(height), img, resize.Bilinear)
  37. var b []byte
  38. buf := bytes.NewBuffer(b)
  39. switch format {
  40. case "png":
  41. err = png.Encode(buf, img)
  42. case "jpeg":
  43. err = jpeg.Encode(buf, img, nil)
  44. default:
  45. return fmt.Errorf("%s image type is not currently supported", format), false
  46. }
  47. if nil != err {
  48. return fmt.Errorf("image encode error:%v", err), false
  49. }
  50. return buf.Bytes(), true
  51. }
  52. func (f *imageResize) IsAggregate() bool {
  53. return false
  54. }