github.com/go-oss/image@v0.1.1-0.20230517025328-001b78555e78/imageutil/mimetype.go (about)

     1  package imageutil
     2  
     3  import (
     4  	"net/http"
     5  )
     6  
     7  // MIMEType represents MIME type for image file.
     8  type MIMEType uint8
     9  
    10  const (
    11  	// UndefinedType represents unknown image type.
    12  	UndefinedType MIMEType = iota
    13  	// JPEG represents jpeg image type.
    14  	JPEG
    15  	// PNG represents png image type.
    16  	PNG
    17  	// GIF represents gif image type.
    18  	GIF
    19  	// WEBP represents webp image type.
    20  	WEBP
    21  )
    22  
    23  func (m MIMEType) String() string {
    24  	switch m {
    25  	case JPEG:
    26  		return "image/jpeg"
    27  	case PNG:
    28  		return "image/png"
    29  	case GIF:
    30  		return "image/gif"
    31  	case WEBP:
    32  		return "image/webp"
    33  	default:
    34  		return ""
    35  	}
    36  }
    37  
    38  // Ext returns file extension.
    39  func (m MIMEType) Ext() string {
    40  	switch m {
    41  	case JPEG:
    42  		return ".jpg"
    43  	case PNG:
    44  		return ".png"
    45  	case GIF:
    46  		return ".gif"
    47  	case WEBP:
    48  		return ".webp"
    49  	default:
    50  		return ""
    51  	}
    52  }
    53  
    54  // MIMETypeByType returns MIMEType by type string.
    55  func MIMETypeByType(typ string) MIMEType {
    56  	switch typ {
    57  	case "image/jpeg":
    58  		return JPEG
    59  	case "image/png":
    60  		return PNG
    61  	case "image/gif":
    62  		return GIF
    63  	case "image/webp":
    64  		return WEBP
    65  	default:
    66  		return MIMEType(0)
    67  	}
    68  }
    69  
    70  // DetectMimeType detects MIMEType for image file.
    71  func DetectMimeType(fileHeader []byte) MIMEType {
    72  	contentType := http.DetectContentType(fileHeader)
    73  	return MIMETypeByType(contentType)
    74  }