コード例 #1
0
ファイル: avatar.go プロジェクト: Gufran/initials-avatar
// Draw draws an image base on the name and size.
// Only initials of name will be draw.
// The size is the side length of the square image. Image is encoded to bytes.
func (a *InitialsAvatar) DrawToBytes(name string, size int) ([]byte, error) {
	if size <= 0 {
		size = 48 // default size
	}
	name = strings.TrimSpace(name)
	firstRune := []rune(name)[0]
	if !isHan(firstRune) && !unicode.IsLetter(firstRune) {
		return nil, ErrUnsupportChar
	}
	initials := getInitials(name)
	bgcolor := getColorByName(name)

	// get from cache
	v, ok := a.cache.GetBytes(lru.Key(initials))
	if ok {
		return v, nil
	}

	m := a.drawer.Draw(initials, size, bgcolor)

	var buf bytes.Buffer
	err := png.Encode(&buf, m)
	if err != nil {
		return nil, err
	}
	// set cache
	a.cache.SetBytes(lru.Key(initials), buf.Bytes())

	return buf.Bytes(), nil
}
コード例 #2
0
ファイル: avatar.go プロジェクト: doubaokun/initials-avatar
// DrawToBytes draws an image base on the name and size.
// Only initials of name will be draw.
// The size is the side length of the square image. Image is encoded to bytes.
//
// You can optionaly specify the encoding of the file. the supported values are png and jpeg for
// png images and jpeg images respectively. if no encoding is specified then png is used.
func (a *InitialsAvatar) DrawToBytes(name string, size int, encoding ...string) ([]byte, error) {
	if size <= 0 {
		size = 48 // default size
	}
	name = strings.TrimSpace(name)
	firstRune := []rune(name)[0]
	if !isHan(firstRune) && !unicode.IsLetter(firstRune) {
		return nil, ErrUnsupportChar
	}
	initials := getInitials(name)
	bgcolor := getColorByName(name)

	// get from cache
	v, ok := a.cache.GetBytes(lru.Key(initials))
	if ok {
		return v, nil
	}

	m := a.drawer.Draw(initials, size, bgcolor)

	// encode the image
	var buf bytes.Buffer
	enc := "png"
	if len(encoding) > 0 {
		enc = encoding[0]
	}
	switch enc {
	case "jpeg":
		err := jpeg.Encode(&buf, m, nil)
		if err != nil {
			return nil, err
		}
	case "png":
		err := png.Encode(&buf, m)
		if err != nil {
			return nil, err
		}
	default:
		return nil, ErrUnsupportedEncoding
	}

	// set cache
	a.cache.SetBytes(lru.Key(initials), buf.Bytes())

	return buf.Bytes(), nil
}