Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added resize photo function to helpers.go #600 #661

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
40 changes: 40 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down