48 lines
988 B
Go
Raw Normal View History

2017-06-13 11:23:54 +00:00
package main
2017-06-13 12:47:17 +00:00
import (
2017-06-13 15:06:30 +00:00
"bytes"
"fmt"
2017-06-13 12:47:17 +00:00
"image"
"github.com/animenotifier/arn"
2017-06-13 15:06:30 +00:00
"github.com/parnurzeal/gorequest"
2017-06-13 12:47:17 +00:00
)
2017-06-13 11:23:54 +00:00
// Avatar represents a single image and the name of the format.
type Avatar struct {
2017-06-13 12:47:17 +00:00
User *arn.User
2017-06-13 11:23:54 +00:00
Image image.Image
Data []byte
Format string
}
2017-06-13 15:06:30 +00:00
// String returns a text representation of the format, width and height.
func (avatar *Avatar) String() string {
return fmt.Sprint(avatar.Format, " | ", avatar.Image.Bounds().Dx(), "x", avatar.Image.Bounds().Dy())
}
// AvatarFromURL downloads and decodes the image from an URL and creates an Avatar.
func AvatarFromURL(url string, user *arn.User) *Avatar {
// Download
response, data, networkErr := gorequest.New().Get(url).EndBytes()
if networkErr != nil || response.StatusCode != 200 {
return nil
}
// Decode
img, format, decodeErr := image.Decode(bytes.NewReader(data))
if decodeErr != nil {
return nil
}
return &Avatar{
User: user,
Image: img,
Data: data,
Format: format,
}
}