2018-06-09 04:25:16 +00:00
|
|
|
package thumbnail
|
|
|
|
|
|
|
|
import (
|
2018-06-09 04:39:41 +00:00
|
|
|
"image"
|
2018-06-09 04:25:16 +00:00
|
|
|
"mime"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DirectThumbnailer struct {
|
|
|
|
cfg Config
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewThumbnailer(w, h int) Thumbnailer {
|
|
|
|
opts := DefaultConfig
|
|
|
|
opts.Width = w
|
|
|
|
opts.Height = h
|
|
|
|
|
|
|
|
return NewThumbnailerEx(&opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewThumbnailerEx(opts *Config) Thumbnailer {
|
|
|
|
if opts == nil {
|
|
|
|
opts = &DefaultConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
return &DirectThumbnailer{cfg: *opts}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (this *DirectThumbnailer) RenderFile(absPath string) ([]byte, error) {
|
|
|
|
mimeType := mime.TypeByExtension(filepath.Ext(absPath))
|
|
|
|
|
2018-06-09 04:39:41 +00:00
|
|
|
// Decode source
|
|
|
|
|
|
|
|
var src image.Image
|
|
|
|
var err error = nil
|
2018-06-09 04:25:16 +00:00
|
|
|
if strings.HasPrefix(mimeType, `image/`) {
|
2018-06-09 04:39:41 +00:00
|
|
|
src, err = this.imageSnapshot(absPath, mimeType)
|
2018-06-09 04:25:16 +00:00
|
|
|
|
|
|
|
} else if strings.HasPrefix(mimeType, `video/`) {
|
2018-06-09 04:39:41 +00:00
|
|
|
src, err = this.videoSnapshot(absPath)
|
2018-06-09 04:25:16 +00:00
|
|
|
|
|
|
|
} else {
|
|
|
|
return nil, ErrUnsupportedFiletype
|
|
|
|
|
|
|
|
}
|
2018-06-09 04:39:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Scale
|
|
|
|
|
2018-06-09 05:17:57 +00:00
|
|
|
dest, err := this.scaleImage(src)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-06-09 04:39:41 +00:00
|
|
|
|
|
|
|
// Rasterise result
|
|
|
|
|
|
|
|
return this.encode(dest)
|
2018-06-09 04:25:16 +00:00
|
|
|
}
|