discord / lilliput

Resize images and animated GIFs in Go
https://discord.com/blog/how-discord-resizes-150-million-images-every-day-with-go-and-c
Other
1.94k stars 123 forks source link

PNG compression - larger then before #88

Open loeffel-io opened 3 years ago

loeffel-io commented 3 years ago

Hey, i am currently try to compress png and jpg images with lilliput.

While i am uploading pngs the png file sizes are larger then before - with all kind of compression levels (1 to 9):

var EncodeOptions = map[string]map[int]int{
    matchers.TypeJpeg.Extension: {lilliput.JpegQuality: 85},
    matchers.TypePng.Extension:  {lilliput.PngCompression: 9},
}

var fileType types.Type
if fileType = filetype.MatchMap(buf.Bytes(), matchers.Map{
    matchers.TypeJpeg: matchers.Jpeg,
    matchers.TypePng:  matchers.Png,
}); fileType == filetype.Unknown {
    c.AbortWithStatusJSON(h.StatusBadRequest, http.Response(fmt.Errorf("filetype unsupported"), nil))
    return
}

if decoder, err = lilliput.NewDecoder(buf.Bytes()); err != nil {
    c.AbortWithStatusJSON(h.StatusInternalServerError, http.Response(err, nil))
    return
}

defer func() {
    decoder.Close()
}()

if header, err = decoder.Header(); err != nil {
    c.AbortWithStatusJSON(h.StatusInternalServerError, http.Response(err, nil))
    return
}

var ops = lilliput.NewImageOps(8192)

defer func() {
    ops.Close()
}()

var opts = &lilliput.ImageOptions{
    FileType:             fmt.Sprintf(".%s", fileType.Extension),
    Width:                header.Width(),
    Height:               header.Height(),
    ResizeMethod:         lilliput.ImageOpsResize,
    NormalizeOrientation: false,
    EncodeOptions:        EncodeOptions[fileType.Extension],
}

var data = make([]byte, maxSize)

if data, err = ops.Transform(decoder, opts, data); err != nil {
    c.AbortWithStatusJSON(h.StatusInternalServerError, http.Response(err, nil))
    return
}

log.Printf("%d:%d", len(buf.Bytes()), len(data)) // 112319:270094

Before (112 KB)

wonder-day-among-us-21

After (270 KB)

profile (2)

pngCompression 1

the result is 112319:408167

yyong37 commented 3 years ago

the origin image is png8 to png32.. so the image is larger. so if have some func keep png8~ everything will be ok.

loeffel-io commented 3 years ago

so there is no support for png8?