thumbnail.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "bytes"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "github.com/nfnt/resize"
  20. "image"
  21. "image/jpeg"
  22. "image/png"
  23. )
  24. type thumbnail struct {
  25. }
  26. func (f *thumbnail) Validate(args []interface{}) error {
  27. if len(args) != 3 {
  28. return fmt.Errorf("The thumbnail function supports 3 parameters, but got %d", len(args))
  29. }
  30. return nil
  31. }
  32. func (f *thumbnail) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
  33. arg, ok := args[0].([]byte)
  34. if !ok {
  35. return fmt.Errorf("arg[0] is not a bytea, got %v", args[0]), false
  36. }
  37. maxWidth, ok := args[1].(int)
  38. if !ok || 0 > maxWidth {
  39. return fmt.Errorf("arg[1] is not a bigint, got %v", args[1]), false
  40. }
  41. maxHeight, ok := args[2].(int)
  42. if !ok || 0 > maxHeight {
  43. return fmt.Errorf("arg[2] is not a bigint, got %v", args[2]), false
  44. }
  45. img, format, err := image.Decode(bytes.NewReader(arg))
  46. if nil != err {
  47. return fmt.Errorf("image decode error:%v", err), false
  48. }
  49. img = resize.Thumbnail(uint(maxWidth), uint(maxHeight), img, resize.Bilinear)
  50. var b []byte
  51. buf := bytes.NewBuffer(b)
  52. switch format {
  53. case "png":
  54. err = png.Encode(buf, img)
  55. case "jpeg":
  56. err = jpeg.Encode(buf, img, nil)
  57. default:
  58. return fmt.Errorf("%s image type is not currently supported", format), false
  59. }
  60. if nil != err {
  61. return fmt.Errorf("image encode error:%v", err), false
  62. }
  63. return buf.Bytes(), true
  64. }
  65. func (f *thumbnail) IsAggregate() bool {
  66. return false
  67. }