libimage.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package playground
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "errors"
  7. "image"
  8. "image/color"
  9. "image/draw"
  10. "image/gif"
  11. "image/jpeg"
  12. "image/png"
  13. "path"
  14. "strings"
  15. "github.com/robertkrimen/otto"
  16. )
  17. // The playground decodes JPEG, PNG and GIF with the standard library; WebP,
  18. // HEIC and RAW need the server's decoders.
  19. func (r *run) decodeImage(vpath string) (image.Image, string, error) {
  20. b, err := r.fs.ReadFile(vpath)
  21. if err != nil {
  22. return nil, "", fsErr("open", vpath, err)
  23. }
  24. img, format, err := image.Decode(bytes.NewReader(b))
  25. if err != nil {
  26. return nil, "", errors.New("image: unknown format (the playground reads JPEG, PNG and GIF)")
  27. }
  28. return img, format, nil
  29. }
  30. func encodeImage(img image.Image, format string) ([]byte, error) {
  31. var buf bytes.Buffer
  32. var err error
  33. switch format {
  34. case "png":
  35. err = png.Encode(&buf, img)
  36. case "gif":
  37. err = gif.Encode(&buf, img, nil)
  38. default:
  39. err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85})
  40. }
  41. return buf.Bytes(), err
  42. }
  43. // formatFor picks the encoder from a destination file name.
  44. func formatFor(vpath string) string {
  45. switch strings.ToLower(path.Ext(vpath)) {
  46. case ".png":
  47. return "png"
  48. case ".gif":
  49. return "gif"
  50. }
  51. return "jpeg"
  52. }
  53. // resize scales with an area average when shrinking and bilinear sampling
  54. // when enlarging; a side of 0 keeps the aspect ratio.
  55. func resize(src image.Image, w, h int) image.Image {
  56. b := src.Bounds()
  57. sw, sh := b.Dx(), b.Dy()
  58. if sw == 0 || sh == 0 {
  59. return src
  60. }
  61. if w <= 0 && h <= 0 {
  62. w, h = sw, sh
  63. } else if w <= 0 {
  64. w = max(1, sw*h/sh)
  65. } else if h <= 0 {
  66. h = max(1, sh*w/sw)
  67. }
  68. dst := image.NewRGBA(image.Rect(0, 0, w, h))
  69. for y := 0; y < h; y++ {
  70. y0 := b.Min.Y + y*sh/h
  71. y1 := max(y0+1, b.Min.Y+(y+1)*sh/h)
  72. for x := 0; x < w; x++ {
  73. x0 := b.Min.X + x*sw/w
  74. x1 := max(x0+1, b.Min.X+(x+1)*sw/w)
  75. var rr, gg, bb, aa, n uint32
  76. for sy := y0; sy < y1; sy++ {
  77. for sx := x0; sx < x1; sx++ {
  78. cr, cg, cb, ca := src.At(sx, sy).RGBA()
  79. rr, gg, bb, aa = rr+cr, gg+cg, bb+cb, aa+ca
  80. n++
  81. }
  82. }
  83. dst.Set(x, y, color.RGBA64{uint16(rr / n), uint16(gg / n), uint16(bb / n), uint16(aa / n)})
  84. }
  85. }
  86. return dst
  87. }
  88. // fitSize scales w x h down to fit maxW x maxH (0 leaves a side free),
  89. // never up.
  90. func fitSize(w, h, maxW, maxH int) (int, int) {
  91. scale := 1.0
  92. if maxW > 0 && w > maxW {
  93. scale = float64(maxW) / float64(w)
  94. }
  95. if maxH > 0 && float64(h)*scale > float64(maxH) {
  96. scale = float64(maxH) / float64(h)
  97. }
  98. return max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
  99. }
  100. func (r *run) writeImage(dest string, img image.Image) error {
  101. b, err := encodeImage(img, formatFor(dest))
  102. if err != nil {
  103. return err
  104. }
  105. return r.fs.WriteFile(dest, b)
  106. }
  107. func (r *run) injectImagelib(vm *otto.Otto, script string) {
  108. read := func(call otto.FunctionCall, i int) string {
  109. p, _ := argString(call, i)
  110. p = r.relPath(script, p)
  111. if !r.canRead(p) {
  112. r.denied(vm, p)
  113. }
  114. return p
  115. }
  116. write := func(call otto.FunctionCall, i int) string {
  117. p, _ := argString(call, i)
  118. p = r.relPath(script, p)
  119. if !r.canWrite(p) {
  120. r.denied(vm, p)
  121. }
  122. return p
  123. }
  124. intArg := func(call otto.FunctionCall, i int) int {
  125. n, _ := call.Argument(i).ToInteger()
  126. return int(n)
  127. }
  128. vm.Set("_imagelib_getImageDimension", func(call otto.FunctionCall) otto.Value {
  129. p := read(call, 0)
  130. b, err := r.fs.ReadFile(p)
  131. if err != nil {
  132. return r.raise(vm, "ImageLibError", fsErr("open", p, err))
  133. }
  134. cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
  135. if err != nil {
  136. return r.raise(vm, "ImageLibError", err)
  137. }
  138. out, _ := vm.ToValue([]int{cfg.Width, cfg.Height})
  139. return out
  140. })
  141. vm.Set("_imagelib_resizeImage", func(call otto.FunctionCall) otto.Value {
  142. src, dest := read(call, 0), write(call, 1)
  143. img, _, err := r.decodeImage(src)
  144. if err != nil {
  145. return r.raise(vm, "ImageLibError", err)
  146. }
  147. if err := r.writeImage(dest, resize(img, intArg(call, 2), intArg(call, 3))); err != nil {
  148. return r.raise(vm, "ImageLibError", fsErr("open", dest, err))
  149. }
  150. return otto.TrueValue()
  151. })
  152. vm.Set("_imagelib_resizeImageBase64", func(call otto.FunctionCall) otto.Value {
  153. src := read(call, 0)
  154. format, ok := argString(call, 3)
  155. if !ok || (format != "png" && format != "jpeg" && format != "jpg") {
  156. format = "jpeg"
  157. }
  158. if format == "jpg" {
  159. format = "jpeg"
  160. }
  161. img, _, err := r.decodeImage(src)
  162. if err != nil {
  163. return r.raise(vm, "ImageLibError", err)
  164. }
  165. b, err := encodeImage(resize(img, intArg(call, 1), intArg(call, 2)), format)
  166. if err != nil {
  167. return r.raise(vm, "ImageLibError", err)
  168. }
  169. out, _ := vm.ToValue("data:image/" + format + ";base64," + base64.StdEncoding.EncodeToString(b))
  170. return out
  171. })
  172. vm.Set("_imagelib_cropImage", func(call otto.FunctionCall) otto.Value {
  173. src, dest := read(call, 0), write(call, 1)
  174. img, _, err := r.decodeImage(src)
  175. if err != nil {
  176. return r.raise(vm, "ImageLibError", err)
  177. }
  178. x, y, w, h := intArg(call, 2), intArg(call, 3), intArg(call, 4), intArg(call, 5)
  179. b := img.Bounds()
  180. rect := image.Rect(b.Min.X+x, b.Min.Y+y, b.Min.X+x+w, b.Min.Y+y+h).Intersect(b)
  181. if rect.Empty() {
  182. return r.raise(vm, "ImageLibError", errors.New("crop area is outside the image"))
  183. }
  184. dst := image.NewRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy()))
  185. draw.Draw(dst, dst.Bounds(), img, rect.Min, draw.Src)
  186. if err := r.writeImage(dest, dst); err != nil {
  187. return r.raise(vm, "ImageLibError", fsErr("open", dest, err))
  188. }
  189. return otto.TrueValue()
  190. })
  191. vm.Set("_imagelib_loadThumbString", func(call otto.FunctionCall) otto.Value {
  192. p := read(call, 0)
  193. //A file without a thumbnail is an answer, not an error: false
  194. img, _, err := r.decodeImage(p)
  195. if err != nil {
  196. return otto.FalseValue()
  197. }
  198. w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), 480, 480)
  199. b, _ := encodeImage(resize(img, w, h), "jpeg")
  200. out, _ := vm.ToValue(base64.StdEncoding.EncodeToString(b))
  201. return out
  202. })
  203. vm.Set("_imagelib_hasExif", func(call otto.FunctionCall) otto.Value {
  204. p := read(call, 0)
  205. b, err := r.fs.ReadFile(p)
  206. if err != nil {
  207. return r.raise(vm, "ImageLibError", errors.New("File not exists! Given "+p))
  208. }
  209. return boolValue(bytes.Contains(b[:min(len(b), 65536)], []byte("Exif\x00\x00")))
  210. })
  211. vm.Set("_imagelib_getExif", func(call otto.FunctionCall) otto.Value {
  212. p := read(call, 0)
  213. img, format, err := r.decodeImage(p)
  214. if err != nil {
  215. return r.raise(vm, "ImageLibError", err)
  216. }
  217. // The playground does not parse EXIF tags; it reports what it knows.
  218. info := map[string]interface{}{"ImageWidth": img.Bounds().Dx(), "ImageHeight": img.Bounds().Dy(), "Format": format}
  219. b, _ := json.Marshal(info)
  220. r.log("agi", "warn", "imagelib.getExif: the playground returns the image size only; EXIF tags need a server")
  221. out, _ := vm.ToValue(string(b))
  222. return out
  223. })
  224. vm.Set("_imagelib_rawToJPEG", func(call otto.FunctionCall) otto.Value {
  225. return r.raise(vm, "ImageLibError", errors.New("imagelib.rawToJPEG needs the server's RAW decoder; it is not available in the playground"))
  226. })
  227. vm.Set("_imagelib_renderPreview", func(call otto.FunctionCall) otto.Value {
  228. src := read(call, 0)
  229. dest, _ := argString(call, 1)
  230. if dest != "" && dest != "undefined" {
  231. dest = write(call, 1)
  232. } else {
  233. dest = ""
  234. }
  235. img, _, err := r.decodeImage(src)
  236. if err != nil {
  237. panic(vm.MakeCustomError("ImageError", err.Error()))
  238. }
  239. w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), intArg(call, 2), intArg(call, 3))
  240. out := resize(img, w, h)
  241. res := map[string]interface{}{"width": w, "height": h}
  242. if dest == "" {
  243. b, _ := encodeImage(out, "jpeg")
  244. res["dataURL"] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b)
  245. } else {
  246. r.fs.MkdirAll(path.Dir(dest))
  247. if err := r.writeImage(dest, out); err != nil {
  248. panic(vm.MakeCustomError("ImageError", err.Error()))
  249. }
  250. }
  251. v, _ := vm.ToValue(res)
  252. return v
  253. })
  254. vm.Run(`
  255. var imagelib = {};
  256. imagelib.getImageDimension = _imagelib_getImageDimension;
  257. imagelib.resizeImage = _imagelib_resizeImage;
  258. imagelib.resizeImageBase64 = _imagelib_resizeImageBase64;
  259. imagelib.cropImage = _imagelib_cropImage;
  260. imagelib.loadThumbString = _imagelib_loadThumbString;
  261. imagelib.hasExif = _imagelib_hasExif;
  262. imagelib.getExif = _imagelib_getExif;
  263. imagelib.rawToJPEG = _imagelib_rawToJPEG;
  264. imagelib.renderPreview = _imagelib_renderPreview;
  265. `)
  266. }