61 lines
1.1 KiB
Go
Raw Normal View History

2017-06-13 12:47:17 +00:00
package main
import (
"bytes"
"errors"
"image/gif"
"image/jpeg"
"image/png"
"io/ioutil"
"github.com/nfnt/resize"
)
// AvatarOriginalFileOutput ...
type AvatarOriginalFileOutput struct {
Directory string
Size int
}
// SaveAvatar writes the original avatar to the file system.
func (output *AvatarOriginalFileOutput) SaveAvatar(avatar *Avatar) error {
// Determine file extension
2017-07-08 13:40:13 +00:00
extension := avatar.Extension()
2017-06-13 12:47:17 +00:00
2017-07-08 13:40:13 +00:00
if extension == "" {
2017-06-13 12:47:17 +00:00
return errors.New("Unknown format: " + avatar.Format)
}
// Resize if needed
data := avatar.Data
img := avatar.Image
2017-06-14 16:15:08 +00:00
if img.Bounds().Dx() > output.Size {
img = resize.Resize(uint(output.Size), 0, img, resize.Lanczos3)
2017-06-13 12:47:17 +00:00
buffer := new(bytes.Buffer)
var err error
switch extension {
case ".jpg":
err = jpeg.Encode(buffer, img, nil)
case ".png":
err = png.Encode(buffer, img)
case ".gif":
err = gif.Encode(buffer, img, nil)
}
if err != nil {
return err
}
data = buffer.Bytes()
}
2017-07-08 13:40:13 +00:00
// Set user avatar
avatar.User.AvatarExtension = extension
2017-06-13 12:47:17 +00:00
// Write to file
fileName := output.Directory + avatar.User.ID + extension
return ioutil.WriteFile(fileName, data, 0644)
}