package main import ( "bytes" "image" "image/color" "image/jpeg" ) func thumbnail(im image.Image) ([]byte, int, int, error) { b := im.Bounds() w, h := b.Dx(), b.Dy() nw, nh := w, h if w > 256 || h > 256 { if w >= h { nw = 256 nh = max(1, h*256/w) } else { nh = 256 nw = max(1, w*256/h) } } thumb := image.NewRGBA(image.Rect(0, 0, nw, nh)) for y := 0; y < nh; y++ { for x := 0; x < nw; x++ { rr, gg, bb, aa := im.At(b.Min.X+x*w/nw, b.Min.Y+y*h/nh).RGBA() thumb.SetRGBA(x, y, color.RGBA{uint8((rr + 65535 - aa) >> 8), uint8((gg + 65535 - aa) >> 8), uint8((bb + 65535 - aa) >> 8), 255}) } } var out bytes.Buffer if err := jpeg.Encode(&out, thumb, &jpeg.Options{Quality: 85}); err != nil { return nil, 0, 0, err } return out.Bytes(), nw, nh, nil }