photoprism/pkg/fs/mime.go
Michael Mayer a604e9a9c6 Index: Improve file size/resolution checks, add WebP support #1017 #1226
Renames the config flag to from "megapixel-limit" to "resolution-limit".
Adds native support for the WebP image file format.
2022-04-02 18:04:11 +02:00

41 lines
884 B
Go

package fs
import (
"os"
"github.com/h2non/filetype"
)
const (
MimeTypeJpeg = "image/jpeg"
MimeTypePng = "image/png"
MimeTypeGif = "image/gif"
MimeTypeBitmap = "image/bmp"
MimeTypeWebP = "image/webp"
MimeTypeTiff = "image/tiff"
MimeTypeHEIF = "image/heif"
)
// MimeType returns the mime type of a file, an empty string if it is unknown.
func MimeType(filename string) string {
handle, err := os.Open(filename)
if err != nil {
return ""
}
defer handle.Close()
// Only the first 261 bytes are used to sniff the content type.
buffer := make([]byte, 261)
if _, err := handle.Read(buffer); err != nil {
return ""
} else if t, err := filetype.Get(buffer); err == nil && t != filetype.Unknown {
return t.MIME.Value
} else if t := filetype.GetType(NormalizeExt(filename)); t != filetype.Unknown {
return t.MIME.Value
} else {
return ""
}
}