jlelse
/
hugo-micropub
Archived
1
Fork 0
This repository has been archived on 2020-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
hugo-micropub/imagecompression.go

76 lines
1.6 KiB
Go
Raw Normal View History

2020-01-19 09:55:18 +00:00
package main
import (
"errors"
"io/ioutil"
"os"
"sort"
"strings"
2020-07-21 18:42:56 +00:00
tfgo "codeberg.org/jlelse/tinify"
2020-01-19 09:55:18 +00:00
)
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
}