| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277 |
- package playground
- import (
- "bytes"
- "encoding/base64"
- "encoding/json"
- "errors"
- "image"
- "image/color"
- "image/draw"
- "image/gif"
- "image/jpeg"
- "image/png"
- "path"
- "strings"
- "github.com/robertkrimen/otto"
- )
- // The playground decodes JPEG, PNG and GIF with the standard library; WebP,
- // HEIC and RAW need the server's decoders.
- func (r *run) decodeImage(vpath string) (image.Image, string, error) {
- b, err := r.fs.ReadFile(vpath)
- if err != nil {
- return nil, "", fsErr("open", vpath, err)
- }
- img, format, err := image.Decode(bytes.NewReader(b))
- if err != nil {
- return nil, "", errors.New("image: unknown format (the playground reads JPEG, PNG and GIF)")
- }
- return img, format, nil
- }
- func encodeImage(img image.Image, format string) ([]byte, error) {
- var buf bytes.Buffer
- var err error
- switch format {
- case "png":
- err = png.Encode(&buf, img)
- case "gif":
- err = gif.Encode(&buf, img, nil)
- default:
- err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 85})
- }
- return buf.Bytes(), err
- }
- // formatFor picks the encoder from a destination file name.
- func formatFor(vpath string) string {
- switch strings.ToLower(path.Ext(vpath)) {
- case ".png":
- return "png"
- case ".gif":
- return "gif"
- }
- return "jpeg"
- }
- // resize scales with an area average when shrinking and bilinear sampling
- // when enlarging; a side of 0 keeps the aspect ratio.
- func resize(src image.Image, w, h int) image.Image {
- b := src.Bounds()
- sw, sh := b.Dx(), b.Dy()
- if sw == 0 || sh == 0 {
- return src
- }
- if w <= 0 && h <= 0 {
- w, h = sw, sh
- } else if w <= 0 {
- w = max(1, sw*h/sh)
- } else if h <= 0 {
- h = max(1, sh*w/sw)
- }
- dst := image.NewRGBA(image.Rect(0, 0, w, h))
- for y := 0; y < h; y++ {
- y0 := b.Min.Y + y*sh/h
- y1 := max(y0+1, b.Min.Y+(y+1)*sh/h)
- for x := 0; x < w; x++ {
- x0 := b.Min.X + x*sw/w
- x1 := max(x0+1, b.Min.X+(x+1)*sw/w)
- var rr, gg, bb, aa, n uint32
- for sy := y0; sy < y1; sy++ {
- for sx := x0; sx < x1; sx++ {
- cr, cg, cb, ca := src.At(sx, sy).RGBA()
- rr, gg, bb, aa = rr+cr, gg+cg, bb+cb, aa+ca
- n++
- }
- }
- dst.Set(x, y, color.RGBA64{uint16(rr / n), uint16(gg / n), uint16(bb / n), uint16(aa / n)})
- }
- }
- return dst
- }
- // fitSize scales w x h down to fit maxW x maxH (0 leaves a side free),
- // never up.
- func fitSize(w, h, maxW, maxH int) (int, int) {
- scale := 1.0
- if maxW > 0 && w > maxW {
- scale = float64(maxW) / float64(w)
- }
- if maxH > 0 && float64(h)*scale > float64(maxH) {
- scale = float64(maxH) / float64(h)
- }
- return max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
- }
- func (r *run) writeImage(dest string, img image.Image) error {
- b, err := encodeImage(img, formatFor(dest))
- if err != nil {
- return err
- }
- return r.fs.WriteFile(dest, b)
- }
- func (r *run) injectImagelib(vm *otto.Otto, script string) {
- read := func(call otto.FunctionCall, i int) string {
- p, _ := argString(call, i)
- p = r.relPath(script, p)
- if !r.canRead(p) {
- r.denied(vm, p)
- }
- return p
- }
- write := func(call otto.FunctionCall, i int) string {
- p, _ := argString(call, i)
- p = r.relPath(script, p)
- if !r.canWrite(p) {
- r.denied(vm, p)
- }
- return p
- }
- intArg := func(call otto.FunctionCall, i int) int {
- n, _ := call.Argument(i).ToInteger()
- return int(n)
- }
- vm.Set("_imagelib_getImageDimension", func(call otto.FunctionCall) otto.Value {
- p := read(call, 0)
- b, err := r.fs.ReadFile(p)
- if err != nil {
- return r.raise(vm, "ImageLibError", fsErr("open", p, err))
- }
- cfg, _, err := image.DecodeConfig(bytes.NewReader(b))
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- out, _ := vm.ToValue([]int{cfg.Width, cfg.Height})
- return out
- })
- vm.Set("_imagelib_resizeImage", func(call otto.FunctionCall) otto.Value {
- src, dest := read(call, 0), write(call, 1)
- img, _, err := r.decodeImage(src)
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- if err := r.writeImage(dest, resize(img, intArg(call, 2), intArg(call, 3))); err != nil {
- return r.raise(vm, "ImageLibError", fsErr("open", dest, err))
- }
- return otto.TrueValue()
- })
- vm.Set("_imagelib_resizeImageBase64", func(call otto.FunctionCall) otto.Value {
- src := read(call, 0)
- format, ok := argString(call, 3)
- if !ok || (format != "png" && format != "jpeg" && format != "jpg") {
- format = "jpeg"
- }
- if format == "jpg" {
- format = "jpeg"
- }
- img, _, err := r.decodeImage(src)
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- b, err := encodeImage(resize(img, intArg(call, 1), intArg(call, 2)), format)
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- out, _ := vm.ToValue("data:image/" + format + ";base64," + base64.StdEncoding.EncodeToString(b))
- return out
- })
- vm.Set("_imagelib_cropImage", func(call otto.FunctionCall) otto.Value {
- src, dest := read(call, 0), write(call, 1)
- img, _, err := r.decodeImage(src)
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- x, y, w, h := intArg(call, 2), intArg(call, 3), intArg(call, 4), intArg(call, 5)
- b := img.Bounds()
- rect := image.Rect(b.Min.X+x, b.Min.Y+y, b.Min.X+x+w, b.Min.Y+y+h).Intersect(b)
- if rect.Empty() {
- return r.raise(vm, "ImageLibError", errors.New("crop area is outside the image"))
- }
- dst := image.NewRGBA(image.Rect(0, 0, rect.Dx(), rect.Dy()))
- draw.Draw(dst, dst.Bounds(), img, rect.Min, draw.Src)
- if err := r.writeImage(dest, dst); err != nil {
- return r.raise(vm, "ImageLibError", fsErr("open", dest, err))
- }
- return otto.TrueValue()
- })
- vm.Set("_imagelib_loadThumbString", func(call otto.FunctionCall) otto.Value {
- p := read(call, 0)
- //A file without a thumbnail is an answer, not an error: false
- img, _, err := r.decodeImage(p)
- if err != nil {
- return otto.FalseValue()
- }
- w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), 480, 480)
- b, _ := encodeImage(resize(img, w, h), "jpeg")
- out, _ := vm.ToValue(base64.StdEncoding.EncodeToString(b))
- return out
- })
- vm.Set("_imagelib_hasExif", func(call otto.FunctionCall) otto.Value {
- p := read(call, 0)
- b, err := r.fs.ReadFile(p)
- if err != nil {
- return r.raise(vm, "ImageLibError", errors.New("File not exists! Given "+p))
- }
- return boolValue(bytes.Contains(b[:min(len(b), 65536)], []byte("Exif\x00\x00")))
- })
- vm.Set("_imagelib_getExif", func(call otto.FunctionCall) otto.Value {
- p := read(call, 0)
- img, format, err := r.decodeImage(p)
- if err != nil {
- return r.raise(vm, "ImageLibError", err)
- }
- // The playground does not parse EXIF tags; it reports what it knows.
- info := map[string]interface{}{"ImageWidth": img.Bounds().Dx(), "ImageHeight": img.Bounds().Dy(), "Format": format}
- b, _ := json.Marshal(info)
- r.log("agi", "warn", "imagelib.getExif: the playground returns the image size only; EXIF tags need a server")
- out, _ := vm.ToValue(string(b))
- return out
- })
- vm.Set("_imagelib_rawToJPEG", func(call otto.FunctionCall) otto.Value {
- return r.raise(vm, "ImageLibError", errors.New("imagelib.rawToJPEG needs the server's RAW decoder; it is not available in the playground"))
- })
- vm.Set("_imagelib_renderPreview", func(call otto.FunctionCall) otto.Value {
- src := read(call, 0)
- dest, _ := argString(call, 1)
- if dest != "" && dest != "undefined" {
- dest = write(call, 1)
- } else {
- dest = ""
- }
- img, _, err := r.decodeImage(src)
- if err != nil {
- panic(vm.MakeCustomError("ImageError", err.Error()))
- }
- w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), intArg(call, 2), intArg(call, 3))
- out := resize(img, w, h)
- res := map[string]interface{}{"width": w, "height": h}
- if dest == "" {
- b, _ := encodeImage(out, "jpeg")
- res["dataURL"] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b)
- } else {
- r.fs.MkdirAll(path.Dir(dest))
- if err := r.writeImage(dest, out); err != nil {
- panic(vm.MakeCustomError("ImageError", err.Error()))
- }
- }
- v, _ := vm.ToValue(res)
- return v
- })
- vm.Run(`
- var imagelib = {};
- imagelib.getImageDimension = _imagelib_getImageDimension;
- imagelib.resizeImage = _imagelib_resizeImage;
- imagelib.resizeImageBase64 = _imagelib_resizeImageBase64;
- imagelib.cropImage = _imagelib_cropImage;
- imagelib.loadThumbString = _imagelib_loadThumbString;
- imagelib.hasExif = _imagelib_hasExif;
- imagelib.getExif = _imagelib_getExif;
- imagelib.rawToJPEG = _imagelib_rawToJPEG;
- imagelib.renderPreview = _imagelib_renderPreview;
- `)
- }
|