imagefit
import "github.com/barevoidco/zelk/core/imagefit"Package imagefit fits an image to what a model takes: small enough to send, and no larger than a model looks at. The Read tool fits the image files it returns, and a host fits an image a user pastes or drops before attaching it to a message. AdmitImages enforces the shared admission rule at driver boundaries without changing structural validation of old logs. It uses only the standard library’s decoders.
Constants
Section titled “Constants”const MaxPixels = 64_000_000MaxPixels is the most pixels of an image Fit decodes. Decoded, an image takes up to four bytes a pixel whatever its file’s size, so the bound keeps a small file from costing gigabytes. It admits a 50-megapixel photo.
const MaxSide = 2000MaxSide is the longest side Fit leaves an image: models scale larger ones down themselves, so sending more spends bytes and tokens for nothing.
Variables
Section titled “Variables”var ErrNotImage = errors.New("not a PNG, JPEG, GIF or WebP image")ErrNotImage reports data that is no image Fit can read.
var ErrTooLarge = errors.New("the image is too large")ErrTooLarge reports an image Fit can’t bring within its bounds: one of more than MaxPixels, or one that doesn’t fit however small.
AdmitImages
Section titled “AdmitImages”func AdmitImages(parts []history.Part, maxBytes, totalBytes int) []history.PartAdmitImages returns a copy of parts with untrusted images made suitable for model input. Supported bytes are sniffed, decoded and fitted to maxBytes and the remaining totalBytes budget, then labelled with their actual type. Unusable images become text naming their declared type and size; other content is preserved. GIF inputs become static PNG first frames, since providers reject animated GIFs. Blob references without resolved bytes are not admitted. Validation of recorded items remains structural.
func Fit(data []byte, maxBytes int) ([]byte, error)Fit returns data as an image of at most maxBytes, no side of it longer than MaxSide. An image within both is returned as it is. A larger one is scaled down and encoded again: as PNG if that fits, as JPEG otherwise, smaller each time until it fits. Of an animated GIF that leaves the first frame.
Fit decodes an image it scales, which takes memory by its pixels, up to MaxPixels of them, and processor time to match.
Example
A capture wider than a model looks at is scaled down, keeping its shape.
var capture bytes.Bufferif err := png.Encode(&capture, image.NewRGBA(image.Rect(0, 0, 4000, 1000))); err != nil { fmt.Println(err) return}data, err := imagefit.Fit(capture.Bytes(), 3_500_000)if err != nil { fmt.Println(err) return}cfg, format, _ := image.DecodeConfig(bytes.NewReader(data))fmt.Println(format, cfg.Width, cfg.Height)// Output: png 2000 500Output:
png 2000 500