hugo-micropub/imagecompression.go

75 lines
1.6 KiB
Go
Raw Normal View History

2020-01-19 09:55:18 +00:00
package main
import (
2020-01-23 20:56:02 +00:00
tfgo "codeberg.org/jlelse/tinify"
2020-01-19 09:55:18 +00:00
"errors"
"io/ioutil"
"os"
"sort"
"strings"
)
type ImageCompression interface {
Compress(url string) (location string, err error)
}
// Tinify
type Tinify struct {
// API Key
key string
}
2020-04-20 18:59:11 +00:00
func (t *Tinify) Compress(url string) (location string, err error) {
2020-01-19 09:55:18 +00:00
fileExtension := func() string {
spliced := strings.Split(url, ".")
return spliced[len(spliced)-1]
}()
supportedTypes := []string{"jpg", "jpeg", "png"}
sort.Strings(supportedTypes)
i := sort.SearchStrings(supportedTypes, strings.ToLower(fileExtension))
if !(i < len(supportedTypes) && supportedTypes[i] == strings.ToLower(fileExtension)) {
err = errors.New("file not supported")
return
}
tfgo.SetKey(t.key)
s, e := tfgo.FromUrl(url)
if e != nil {
err = errors.New("failed to compress file")
return
}
2020-01-23 20:56:02 +00:00
e = s.Resize(&tfgo.ResizeOption{
Method: tfgo.ResizeMethodScale,
Width: 2000,
})
if e != nil {
err = errors.New("failed to resize file")
return
}
2020-01-19 09:55:18 +00:00
file, e := ioutil.TempFile("", "tiny-*."+fileExtension)
if e != nil {
err = errors.New("failed to create temporary file")
return
}
defer func() {
2020-04-20 21:04:01 +00:00
_ = file.Close()
2020-01-19 09:55:18 +00:00
_ = os.Remove(file.Name())
}()
e = s.ToFile(file.Name())
if e != nil {
err = errors.New("failed to save compressed file")
return
}
hashFile, e := os.Open(file.Name())
defer func() { _ = hashFile.Close() }()
if e != nil {
err = errors.New("failed to open temporary file")
return
}
fileName, err := getSHA256(hashFile)
if err != nil {
return
}
location, err = SelectedMediaStorage.Upload(fileName+"."+fileExtension, file)
return
}