package main import ( "image" "net/http" "strconv" "strings" "github.com/chai2010/webp" xdraw "golang.org/x/image/draw" "inou/lib" ) func handleImage(w http.ResponseWriter, r *http.Request) { ctx := getAccessContextOrFail(w, r) if ctx == nil { return } hexID := strings.TrimPrefix(r.URL.Path, "/image/") if len(hexID) != 16 { http.Error(w, "Invalid ID", http.StatusBadRequest) return } opts := &lib.ImageOpts{} if wc := r.URL.Query().Get("wc"); wc != "" { opts.WC, _ = strconv.ParseFloat(wc, 64) } if ww := r.URL.Query().Get("ww"); ww != "" { opts.WW, _ = strconv.ParseFloat(ww, 64) } img, err := lib.ImageGet(ctx.AccessorID, hexID, opts) if err != nil { http.Error(w, "Image not found", http.StatusNotFound) return } // Resize if either dimension exceeds maxDim (default 2000 for Claude API) maxDim := 2000 if md := r.URL.Query().Get("maxdim"); md != "" { if v, err := strconv.Atoi(md); err == nil && v > 0 { maxDim = v } } bounds := img.Bounds() w0, h0 := bounds.Dx(), bounds.Dy() if w0 > maxDim || h0 > maxDim { scale := float64(maxDim) / float64(max(w0, h0)) newW := int(float64(w0) * scale) newH := int(float64(h0) * scale) resized := image.NewRGBA(image.Rect(0, 0, newW, newH)) xdraw.BiLinear.Scale(resized, resized.Bounds(), img, bounds, xdraw.Over, nil) img = resized } w.Header().Set("Content-Type", "image/webp") w.Header().Set("Cache-Control", "public, max-age=86400") webp.Encode(w, img, &webp.Options{Lossless: true}) }