package webread import ( "bytes" "encoding/json" "image" "image/draw" "image/gif" "image/jpeg" "image/png" "mime" "strings" "unicode/utf8" "amadan.net/oficina/equipo/internal/attach" ) // sniff names what body is from its bytes. kind is KindImage for PNG, // JPEG and GIF, KindText for text, and "" for anything refused; typ is // the media type the bytes show. declared, the server's Content-Type, // only labels plain text as CSS or Markdown: it decides nothing. func sniff(body []byte, declared string) (kind, typ string) { switch m := attach.Sniff(body); m { case attach.PNG, attach.JPEG, attach.GIF: return KindImage, m case "": default: return "", m } if !isText(body) { return "", "application/octet-stream" } head := strings.ToLower(strings.TrimLeft(string(body[:min(len(body), 1024)]), "\ufeff \t\r\n\f")) if strings.HasPrefix(head, " MaxPixels { return nil, 0, 0, ReasonPixels } img, err := decode(bytes.NewReader(body)) if err != nil { return nil, 0, 0, ReasonImageInvalid } b := img.Bounds() if b.Dx() <= 0 || b.Dy() <= 0 || int64(b.Dx())*int64(b.Dy()) > MaxPixels { return nil, 0, 0, ReasonPixels } rgba := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy())) draw.Draw(rgba, rgba.Bounds(), img, b.Min, draw.Src) if w, h = b.Dx(), b.Dy(); max(w, h) > MaxEdge { if w >= h { w, h = MaxEdge, max(1, h*MaxEdge/w) } else { w, h = max(1, w*MaxEdge/h), MaxEdge } rgba = shrink(rgba, w, h) } var buf bytes.Buffer if err = png.Encode(&buf, rgba); err != nil { return nil, 0, 0, ReasonImageInvalid } if buf.Len() > MaxImageFile { return nil, 0, 0, ReasonTooLarge } return buf.Bytes(), w, h, "" } // shrink is an area average over premultiplied RGBA: each output pixel is // the mean of the source pixels it covers. func shrink(src *image.RGBA, w, h int) *image.RGBA { sw, sh := src.Rect.Dx(), src.Rect.Dy() dst := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { y0, y1 := y*sh/h, max((y+1)*sh/h, y*sh/h+1) for x := 0; x < w; x++ { x0, x1 := x*sw/w, max((x+1)*sw/w, x*sw/w+1) var s [4]uint64 var n uint64 for sy := y0; sy < y1; sy++ { row := src.Pix[sy*src.Stride:] for sx := x0; sx < x1; sx++ { p := row[sx*4:] s[0], s[1], s[2], s[3] = s[0]+uint64(p[0]), s[1]+uint64(p[1]), s[2]+uint64(p[2]), s[3]+uint64(p[3]) n++ } } d := dst.Pix[y*dst.Stride+x*4:] d[0], d[1], d[2], d[3] = uint8(s[0]/n), uint8(s[1]/n), uint8(s[2]/n), uint8(s[3]/n) } } return dst }