thumbnail/Thumbnailer.go

90 lines
1.5 KiB
Go
Raw Normal View History

2016-11-18 06:44:27 +00:00
package thumbnail
import (
"fmt"
"image/jpeg"
"image/png"
"os"
"strings"
2016-11-18 07:02:28 +00:00
lru "github.com/hashicorp/golang-lru"
2016-11-18 06:44:27 +00:00
)
type Thumbnailer struct {
2016-11-18 07:02:28 +00:00
Width int
Height int
2016-11-18 06:44:27 +00:00
2016-11-18 07:02:28 +00:00
thumbCache *lru.Cache // threadsafe
2016-11-18 06:44:27 +00:00
}
2016-11-18 07:02:28 +00:00
func NewThumbnailer(Width, Height, MaxCacheSize int) *Thumbnailer {
thumbCache, err := lru.New(MaxCacheSize)
if err != nil {
panic(err)
}
2016-11-18 06:44:27 +00:00
return &Thumbnailer{
2016-11-18 07:02:28 +00:00
Width: Width,
Height: Height,
thumbCache: thumbCache,
2016-11-18 06:44:27 +00:00
}
}
func (this *Thumbnailer) RenderFile(absPath string) ([]byte, error) {
2016-11-18 07:02:28 +00:00
thumb, ok := this.thumbCache.Get(absPath)
2016-11-18 06:44:27 +00:00
if ok {
2016-11-18 07:02:28 +00:00
return thumb.([]byte), nil
2016-11-18 06:44:27 +00:00
}
// Add to cache
2016-11-18 07:02:28 +00:00
thumb, err := this.RenderFile_NoCache(absPath)
2016-11-18 06:44:27 +00:00
if err != nil {
return nil, err
}
2016-11-18 07:02:28 +00:00
this.thumbCache.Add(absPath, thumb)
return thumb.([]byte), nil
2016-11-18 06:44:27 +00:00
}
func (this *Thumbnailer) RenderFile_NoCache(absPath string) ([]byte, error) {
fh, err := os.OpenFile(absPath, os.O_RDONLY, 0400)
if err != nil {
return nil, err
}
defer fh.Close()
if len(absPath) < 4 {
return nil, fmt.Errorf("No extension on filename")
}
extension := strings.ToLower(absPath[len(absPath)-4:])
2016-11-18 06:44:27 +00:00
switch extension {
case ".jpg", "jpeg":
src, err := jpeg.Decode(fh)
if err != nil {
return nil, err
}
2016-11-18 06:44:27 +00:00
return this.RenderScaledImage(src)
2016-11-18 06:44:27 +00:00
case ".png":
src, err := png.Decode(fh)
if err != nil {
return nil, err
}
2016-11-18 06:44:27 +00:00
return this.RenderScaledImage(src)
case ".avi", ".mkv", ".mp4", ".ogm", ".wmv":
return this.RenderScaledFfmpeg(absPath)
default:
return nil, fmt.Errorf("No thumbnailer for file type")
2016-11-18 06:44:27 +00:00
}
}