Files
ocis/pkg/thumbnail/encoding.go
T

70 lines
1.4 KiB
Go
Raw Normal View History

2020-03-26 09:49:37 +01:00
package thumbnail
2020-03-03 16:40:02 +01:00
import (
"image"
"image/jpeg"
"image/png"
"io"
"strings"
)
2020-03-09 17:03:33 +01:00
// Encoder encodes the thumbnail to a specific format.
2020-03-03 16:40:02 +01:00
type Encoder interface {
2020-03-09 17:03:33 +01:00
// Encode encodes the image to a format.
2020-03-03 16:40:02 +01:00
Encode(io.Writer, image.Image) error
2020-03-09 17:03:33 +01:00
// Types returns the formats suffixes.
2020-03-03 16:40:02 +01:00
Types() []string
2020-03-18 11:13:09 +01:00
// MimeType returns the mimetype used by the encoder.
MimeType() string
2020-03-03 16:40:02 +01:00
}
2020-03-09 17:03:33 +01:00
// PngEncoder encodes to png
2020-03-03 16:40:02 +01:00
type PngEncoder struct{}
2020-03-09 17:03:33 +01:00
// Encode encodes to png format
2020-03-03 16:40:02 +01:00
func (e PngEncoder) Encode(w io.Writer, i image.Image) error {
return png.Encode(w, i)
}
2020-03-09 17:03:33 +01:00
// Types returns the png suffix
2020-03-03 16:40:02 +01:00
func (e PngEncoder) Types() []string {
return []string{"png"}
}
2020-03-18 11:13:09 +01:00
// MimeType returns the mimetype for png files.
func (e PngEncoder) MimeType() string {
return "image/png"
}
2020-03-09 17:03:33 +01:00
// JpegEncoder encodes to jpg.
2020-03-03 16:40:02 +01:00
type JpegEncoder struct{}
2020-03-09 17:03:33 +01:00
// Encode encodes to jpg
2020-03-03 16:40:02 +01:00
func (e JpegEncoder) Encode(w io.Writer, i image.Image) error {
return jpeg.Encode(w, i, nil)
}
2020-03-09 17:03:33 +01:00
// Types returns the jpg suffixes.
2020-03-03 16:40:02 +01:00
func (e JpegEncoder) Types() []string {
return []string{"jpeg", "jpg"}
}
2020-03-18 11:13:09 +01:00
// MimeType returns the mimetype for jpg files.
func (e JpegEncoder) MimeType() string {
return "image/jpeg"
}
2020-03-09 17:03:33 +01:00
// EncoderForType returns the encoder for a given file type
// or nil if the type is not supported.
2020-03-03 16:40:02 +01:00
func EncoderForType(fileType string) Encoder {
switch strings.ToLower(fileType) {
case "png":
return PngEncoder{}
case "jpg":
fallthrough
case "jpeg":
return JpegEncoder{}
default:
return nil
}
}