libimage.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. denied(vm, "Path access denied")
  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. denied(vm, "Path access denied")
  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. r.raise(fsErr("open", p, err))
  133. return otto.FalseValue()
  134. }
  135. cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
  136. if err != nil {
  137. r.raise(err)
  138. return otto.FalseValue()
  139. }
  140. out, _ := vm.ToValue([]int{cfg.Width, cfg.Height})
  141. return out
  142. })
  143. vm.Set("_imagelib_resizeImage", func(call otto.FunctionCall) otto.Value {
  144. src, dest := read(call, 0), write(call, 1)
  145. img, _, err := r.decodeImage(src)
  146. if err != nil {
  147. r.raise(err)
  148. return otto.FalseValue()
  149. }
  150. if err := r.writeImage(dest, resize(img, intArg(call, 2), intArg(call, 3))); err != nil {
  151. r.raise(fsErr("open", dest, err))
  152. return otto.FalseValue()
  153. }
  154. return otto.TrueValue()
  155. })
  156. vm.Set("_imagelib_resizeImageBase64", func(call otto.FunctionCall) otto.Value {
  157. src := read(call, 0)
  158. format, ok := argString(call, 3)
  159. if !ok || (format != "png" && format != "jpeg" && format != "jpg") {
  160. format = "jpeg"
  161. }
  162. if format == "jpg" {
  163. format = "jpeg"
  164. }
  165. img, _, err := r.decodeImage(src)
  166. if err != nil {
  167. r.raise(err)
  168. return otto.FalseValue()
  169. }
  170. b, err := encodeImage(resize(img, intArg(call, 1), intArg(call, 2)), format)
  171. if err != nil {
  172. r.raise(err)
  173. return otto.FalseValue()
  174. }
  175. out, _ := vm.ToValue("data:image/" + format + ";base64," + base64.StdEncoding.EncodeToString(b))
  176. return out
  177. })
  178. vm.Set("_imagelib_cropImage", func(call otto.FunctionCall) otto.Value {
  179. src, dest := read(call, 0), write(call, 1)
  180. img, _, err := r.decodeImage(src)
  181. if err != nil {
  182. r.raise(err)
  183. return otto.FalseValue()
  184. }
  185. x, y, w, h := intArg(call, 2), intArg(call, 3), intArg(call, 4), intArg(call, 5)
  186. b := img.Bounds()
  187. rect := image.Rect(b.Min.X+x, b.Min.Y+y, b.Min.X+x+w, b.Min.Y+y+h).Intersect(b)
  188. if rect.Empty() {
  189. r.raise(errors.New("crop area is outside the image"))
  190. return otto.FalseValue()
  191. }
  192. dst := image.NewRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy()))
  193. draw.Draw(dst, dst.Bounds(), img, rect.Min, draw.Src)
  194. if err := r.writeImage(dest, dst); err != nil {
  195. r.raise(fsErr("open", dest, err))
  196. return otto.FalseValue()
  197. }
  198. return otto.TrueValue()
  199. })
  200. vm.Set("_imagelib_loadThumbString", func(call otto.FunctionCall) otto.Value {
  201. p := read(call, 0)
  202. img, _, err := r.decodeImage(p)
  203. if err != nil {
  204. return otto.FalseValue()
  205. }
  206. w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), 480, 480)
  207. b, _ := encodeImage(resize(img, w, h), "jpeg")
  208. out, _ := vm.ToValue(base64.StdEncoding.EncodeToString(b))
  209. return out
  210. })
  211. vm.Set("_imagelib_hasExif", func(call otto.FunctionCall) otto.Value {
  212. p := read(call, 0)
  213. b, err := r.fs.ReadFile(p)
  214. if err != nil {
  215. return otto.FalseValue()
  216. }
  217. return boolValue(bytes.Contains(b[:min(len(b), 65536)], []byte("Exif\x00\x00")))
  218. })
  219. vm.Set("_imagelib_getExif", func(call otto.FunctionCall) otto.Value {
  220. p := read(call, 0)
  221. img, format, err := r.decodeImage(p)
  222. if err != nil {
  223. r.raise(err)
  224. return otto.FalseValue()
  225. }
  226. // The playground does not parse EXIF tags; it reports what it knows.
  227. info := map[string]interface{}{"ImageWidth": img.Bounds().Dx(), "ImageHeight": img.Bounds().Dy(), "Format": format}
  228. b, _ := json.Marshal(info)
  229. r.log("agi", "warn", "imagelib.getExif: the playground returns the image size only; EXIF tags need a server")
  230. out, _ := vm.ToValue(string(b))
  231. return out
  232. })
  233. vm.Set("_imagelib_rawToJPEG", func(call otto.FunctionCall) otto.Value {
  234. r.raise(errors.New("imagelib.rawToJPEG needs the server's RAW decoder; it is not available in the playground"))
  235. return otto.FalseValue()
  236. })
  237. vm.Set("_imagelib_renderPreview", func(call otto.FunctionCall) otto.Value {
  238. src := read(call, 0)
  239. dest, _ := argString(call, 1)
  240. if dest != "" && dest != "undefined" {
  241. dest = write(call, 1)
  242. } else {
  243. dest = ""
  244. }
  245. img, _, err := r.decodeImage(src)
  246. if err != nil {
  247. panic(vm.MakeCustomError("ImageError", err.Error()))
  248. }
  249. w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), intArg(call, 2), intArg(call, 3))
  250. out := resize(img, w, h)
  251. res := map[string]interface{}{"width": w, "height": h}
  252. if dest == "" {
  253. b, _ := encodeImage(out, "jpeg")
  254. res["dataURL"] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b)
  255. } else {
  256. r.fs.MkdirAll(path.Dir(dest))
  257. if err := r.writeImage(dest, out); err != nil {
  258. panic(vm.MakeCustomError("ImageError", err.Error()))
  259. }
  260. }
  261. v, _ := vm.ToValue(res)
  262. return v
  263. })
  264. vm.Run(`
  265. var imagelib = {};
  266. imagelib.getImageDimension = _imagelib_getImageDimension;
  267. imagelib.resizeImage = _imagelib_resizeImage;
  268. imagelib.resizeImageBase64 = _imagelib_resizeImageBase64;
  269. imagelib.cropImage = _imagelib_cropImage;
  270. imagelib.loadThumbString = _imagelib_loadThumbString;
  271. imagelib.hasExif = _imagelib_hasExif;
  272. imagelib.getExif = _imagelib_getExif;
  273. imagelib.rawToJPEG = _imagelib_rawToJPEG;
  274. imagelib.renderPreview = _imagelib_renderPreview;
  275. `)
  276. }