package outboundimage import ( "bytes" "image" "image/color" "image/draw" "image/jpeg" _ "image/png" "strings" ) const ( // compressMaxEdge bounds the longest side of a published screenshot. Manual // screenshots are captured at 2x-3x, so capping the longest side keeps text // readable while cutting the upload size by an order of magnitude. compressMaxEdge = 1600 // compressJPEGQuality is the re-encode quality for compressed screenshots. compressJPEGQuality = 82 // compressMinBytes skips images that are already small: re-encoding them // saves little upload time and could only lose detail. compressMinBytes = 128 << 10 // compressMaxPixels refuses to decode huge images so one oversized // screenshot cannot exhaust the container's memory. compressMaxPixels = 24 << 20 ) // CompressImage re-encodes an outbound screenshot as a smaller JPEG. It returns // the payload to publish together with its content type, and reports whether // compression applied. Images that are undecodable, already small, animated, or // not smaller after re-encoding are returned untouched, so publishing always // has a usable payload. func CompressImage(data []byte, contentType string) ([]byte, string, bool) { if !compressibleImageType(contentType) || len(data) < compressMinBytes { return data, contentType, false } decoded, _, err := image.Decode(bytes.NewReader(data)) if err != nil { return data, contentType, false } bounds := decoded.Bounds() if bounds.Dx() <= 0 || bounds.Dy() <= 0 || bounds.Dx()*bounds.Dy() > compressMaxPixels { return data, contentType, false } encoded := encodeCompressedImage(downscaleRGBA(flattenToRGBA(decoded), compressMaxEdge)) if encoded == nil || len(encoded) >= len(data) { return data, contentType, false } return encoded, "image/jpeg", true } // compressibleImageType reports whether the content type is a still raster // format this package can decode and re-encode. GIF and WebP are left alone to // preserve animation and format fidelity. func compressibleImageType(contentType string) bool { switch strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0])) { case "image/png", "image/jpeg", "image/jpg": return true default: return false } } func encodeCompressedImage(source image.Image) []byte { var encoded bytes.Buffer if err := jpeg.Encode(&encoded, source, &jpeg.Options{Quality: compressJPEGQuality}); err != nil { return nil } return encoded.Bytes() } // flattenToRGBA copies an image onto an opaque white canvas. JPEG has no alpha // channel, so transparent regions must be composited before encoding or they // would be rendered black. func flattenToRGBA(source image.Image) *image.RGBA { bounds := source.Bounds() target := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy())) draw.Draw(target, target.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src) draw.Draw(target, target.Bounds(), source, bounds.Min, draw.Over) return target } // downscaleRGBA shrinks an image so neither side exceeds maxEdge, averaging the // source pixels that fall into each destination pixel (box filter) so // screenshot text stays legible. func downscaleRGBA(source *image.RGBA, maxEdge int) *image.RGBA { width, height := source.Rect.Dx(), source.Rect.Dy() if width <= maxEdge && height <= maxEdge { return source } targetWidth, targetHeight := width, height if width >= height { targetWidth = maxEdge targetHeight = height * maxEdge / width } else { targetHeight = maxEdge targetWidth = width * maxEdge / height } if targetWidth < 1 { targetWidth = 1 } if targetHeight < 1 { targetHeight = 1 } target := image.NewRGBA(image.Rect(0, 0, targetWidth, targetHeight)) for y := 0; y < targetHeight; y++ { startY := y * height / targetHeight endY := (y + 1) * height / targetHeight if endY <= startY { endY = startY + 1 } for x := 0; x < targetWidth; x++ { startX := x * width / targetWidth endX := (x + 1) * width / targetWidth if endX <= startX { endX = startX + 1 } var red, green, blue, count uint32 for row := startY; row < endY; row++ { line := source.Pix[row*source.Stride:] for column := startX; column < endX; column++ { offset := column * 4 red += uint32(line[offset]) green += uint32(line[offset+1]) blue += uint32(line[offset+2]) count++ } } offset := y*target.Stride + x*4 target.Pix[offset] = uint8(red / count) target.Pix[offset+1] = uint8(green / count) target.Pix[offset+2] = uint8(blue / count) target.Pix[offset+3] = 0xff } } return target }