Skip to content

Commit

Permalink
msgconv/to-whatsapp: re-encode non-NRGBA PNGs
Browse files Browse the repository at this point in the history
  • Loading branch information
tulir committed Dec 5, 2024
1 parent cfc7287 commit ba02ea2
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions pkg/msgconv/to-whatsapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,15 @@ import (
"context"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"net/http"
"strconv"
"strings"
"time"

"github.com/rs/zerolog"
"go.mau.fi/util/ffmpeg"
"go.mau.fi/whatsmeow"
armadillo "go.mau.fi/whatsmeow/proto"
Expand Down Expand Up @@ -184,6 +188,24 @@ func clampTo400(w, h int) (int, int) {
return w, h
}

func reencodeNRGBA(ctx context.Context, data []byte) []byte {
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Failed to decode png for re-encoding")
return data
}
b := img.Bounds()
nrgba := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(nrgba, nrgba.Bounds(), img, b.Min, draw.Src)
var buf bytes.Buffer
if err = png.Encode(&buf, img); err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Failed to re-encode png")
return data
}
zerolog.Ctx(ctx).Debug().Msg("Re-encoded non-NRGBA png")
return buf.Bytes()
}

func (mc *MessageConverter) reuploadMediaToWhatsApp(ctx context.Context, evt *event.Event, content *event.MessageEventContent) (*waMediaTransport.WAMediaTransport, string, error) {
mimeType := content.Info.MimeType
fileName := content.FileName
Expand Down Expand Up @@ -222,6 +244,17 @@ func (mc *MessageConverter) reuploadMediaToWhatsApp(ctx context.Context, evt *ev
}
customInfo["fi.mau.gif"] = true
}
if content.MsgType == event.MsgImage && mimeType == "image/png" {
cfg, err := png.DecodeConfig(bytes.NewReader(data))
if err != nil {
zerolog.Ctx(ctx).Warn().Err(err).Msg("Failed to decode png config")
} else if cfg.ColorModel != color.NRGBAModel {
data = reencodeNRGBA(ctx, data)
}
if content.Info.Width == 0 {
content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
}
}
if content.MsgType == event.MsgImage && content.Info.Width == 0 {
cfg, _, _ := image.DecodeConfig(bytes.NewReader(data))
content.Info.Width, content.Info.Height = cfg.Width, cfg.Height
Expand Down

0 comments on commit ba02ea2

Please sign in to comment.