62 lines
1006 B
Go
62 lines
1006 B
Go
package thumbnail
|
|
|
|
import (
|
|
"image"
|
|
"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))
|
|
|
|
// Decode source
|
|
|
|
var src image.Image
|
|
var err error = nil
|
|
if strings.HasPrefix(mimeType, `image/`) {
|
|
src, err = this.imageSnapshot(absPath, mimeType)
|
|
|
|
} else if strings.HasPrefix(mimeType, `video/`) {
|
|
src, err = this.videoSnapshot(absPath)
|
|
|
|
} else {
|
|
return nil, ErrUnsupportedFiletype
|
|
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Scale
|
|
|
|
dest, err := this.scaleImage(src)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Rasterise result
|
|
|
|
return this.encode(dest)
|
|
}
|