resource_manager/image.go

58 lines
1.2 KiB
Go

package main
import (
"bytes"
"github.com/anthonynsimon/bild/transform"
"image"
"image/jpeg"
"image/png"
"io"
"strings"
)
var mimeTypes = map[string]string{
"jpg": "image/jpg",
"jpeg": "image/jpeg",
"png": "image/png",
"json": "application/json",
"html": "text/html",
"xml": "application/xml",
}
func readMimeType(path string, mimeType string) string {
if mimeType != "" {
return mimeType
}
parts := strings.Split(path, ".")
fileType := parts[len(parts)-1]
if value, exists := mimeTypes[fileType]; exists {
return value
}
return "application/octet-stream"
}
func resizeImage(imageBytes []byte, resizeHeight int) ([]byte, error) {
img, format, err := image.Decode(bytes.NewReader(imageBytes))
if err != nil {
return nil, err
}
var buffer bytes.Buffer
writer := io.Writer(&buffer)
resizeWidth := img.Bounds().Dx() * resizeHeight / img.Bounds().Dy()
img = transform.Resize(img, resizeWidth, resizeHeight, transform.Gaussian)
switch format {
case "png":
err = png.Encode(writer, img)
break
case "jpeg":
err = jpeg.Encode(writer, img, nil)
break
default:
err = jpeg.Encode(writer, img, nil)
}
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}