thumbnail.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. "image"
  19. "image/jpeg"
  20. "image/png"
  21. "github.com/nfnt/resize"
  22. "github.com/lf-edge/ekuiper/pkg/api"
  23. )
  24. type thumbnail struct{}
  25. func (f *thumbnail) Validate(args []interface{}) error {
  26. if len(args) != 3 {
  27. return fmt.Errorf("The thumbnail function supports 3 parameters, but got %d", len(args))
  28. }
  29. return nil
  30. }
  31. func (f *thumbnail) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
  32. arg, ok := args[0].([]byte)
  33. if !ok {
  34. return fmt.Errorf("arg[0] is not a bytea, got %v", args[0]), false
  35. }
  36. maxWidth, ok := args[1].(int)
  37. if !ok || 0 > maxWidth {
  38. return fmt.Errorf("arg[1] is not a bigint, got %v", args[1]), false
  39. }
  40. maxHeight, ok := args[2].(int)
  41. if !ok || 0 > maxHeight {
  42. return fmt.Errorf("arg[2] is not a bigint, got %v", args[2]), false
  43. }
  44. img, format, err := image.Decode(bytes.NewReader(arg))
  45. if nil != err {
  46. return fmt.Errorf("image decode error:%v", err), false
  47. }
  48. img = resize.Thumbnail(uint(maxWidth), uint(maxHeight), img, resize.Bilinear)
  49. var b []byte
  50. buf := bytes.NewBuffer(b)
  51. switch format {
  52. case "png":
  53. err = png.Encode(buf, img)
  54. case "jpeg":
  55. err = jpeg.Encode(buf, img, nil)
  56. default:
  57. return fmt.Errorf("%s image type is not currently supported", format), false
  58. }
  59. if nil != err {
  60. return fmt.Errorf("image encode error:%v", err), false
  61. }
  62. return buf.Bytes(), true
  63. }
  64. func (f *thumbnail) IsAggregate() bool {
  65. return false
  66. }