convert_image.go 983 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
  2. // Use of this source code is governed by the MIT-license that can be
  3. // found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "image"
  8. "image/jpeg"
  9. "io"
  10. "mime"
  11. "path"
  12. "strings"
  13. _ "image/gif"
  14. _ "image/png"
  15. "github.com/nfnt/resize"
  16. )
  17. func isImageMediaType(filename, contentType string) bool {
  18. var mediaType string
  19. if contentType != "" {
  20. mediaType, _, _ = mime.ParseMediaType(contentType)
  21. }
  22. if mediaType == "" {
  23. mediaType = mime.TypeByExtension(path.Ext(filename))
  24. }
  25. return strings.HasPrefix(mediaType, "image/")
  26. }
  27. func convertImage(r io.Reader) ([]byte, error) {
  28. img, _, err := image.Decode(r)
  29. if err != nil {
  30. return nil, err
  31. }
  32. // Scale down
  33. if img.Bounds().Dx() > 600 {
  34. img = resize.Resize(600, 0, img, resize.NearestNeighbor)
  35. }
  36. // Re-encode as low quality jpeg
  37. var buf bytes.Buffer
  38. err = jpeg.Encode(&buf, img, &jpeg.Options{Quality: 40})
  39. return buf.Bytes(), err
  40. }