From 711482e8e0dfe1a78ba93ef1be13d929799e4a4d Mon Sep 17 00:00:00 2001 From: Seyed Mohammad Mahdi Hatami Date: Sat, 17 Jun 2023 22:57:52 +0330 Subject: [PATCH] added resize photo function to helpers.go Signed-off-by: Seyed Mohammad Mahdi Hatami --- go.mod | 2 ++ go.sum | 2 ++ helpers.go | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/go.mod b/go.mod index 167e5e45..5c21bc35 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/go-telegram-bot-api/telegram-bot-api/v5 go 1.16 + +require github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 diff --git a/go.sum b/go.sum index e69de29b..96adbed6 100644 --- a/go.sum +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= +github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= diff --git a/helpers.go b/helpers.go index 3a0e8187..67e32b4d 100644 --- a/helpers.go +++ b/helpers.go @@ -6,9 +6,14 @@ import ( "encoding/hex" "errors" "fmt" + "image" + "image/jpeg" "net/url" + "os" "sort" "strings" + + "github.com/nfnt/resize" ) // NewMessage creates a new Message. @@ -86,6 +91,41 @@ func NewPhoto(chatID int64, file RequestFileData) PhotoConfig { } } +// ResizePhoto resizes the photo to valid dimensions of telegram +func ResizePhoto(fp FilePath) FilePath { + fileHandle, err := os.Open(string(fp)) + defer fileHandle.Close() + if err != nil { + panic("Can't read photo") + } + im, _, err := image.Decode(fileHandle) + w, h := im.Bounds().Dx(), im.Bounds().Dy() + dimSum := w + h + maxDim := 10000 + if dimSum > maxDim { + if err != nil { + panic("Can't read photo") + } + newW, newH := uint(w*maxDim/dimSum), uint(h*maxDim/dimSum) + newImage := resize.Resize(newW, newH, im, resize.Lanczos3) + + // TODO : make a name based on initial file name + outname := "resized_temp.jpg" + + out, err := os.Create(outname) + defer out.Close() + if err != nil { + panic("Can't write photo") + } + err = jpeg.Encode(out, newImage, nil) + + return FilePath(outname) + } else { + return fp + } + +} + // NewPhotoToChannel creates a new photo uploader to send a photo to a channel. // // Note that you must send animated GIFs as a document.