imageUtils.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package utils
  2. import (
  3. "github.com/disintegration/imaging"
  4. "image"
  5. "image/png"
  6. "log"
  7. "mime/multipart"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. )
  12. var (
  13. imgExtMap = map[string]string{
  14. ".jpg": "image/jpeg",
  15. ".jpeg": "image/jpeg",
  16. ".png": "image/png",
  17. }
  18. )
  19. func CheckImageFormat(fileName string, file multipart.File, header *multipart.FileHeader) bool {
  20. ext := strings.ToLower(filepath.Ext(fileName))
  21. contentType := header.Header.Get("Content-Type")
  22. if imgExtMap[ext] == contentType {
  23. return true
  24. }
  25. return false
  26. }
  27. func ImageResize(imageSrc string, maxDimension int) (string, error) {
  28. file, err := os.Open(imageSrc)
  29. if err != nil {
  30. log.Printf("打开图片失败: %v", err)
  31. return "", err
  32. }
  33. defer file.Close()
  34. // 解码图片
  35. img, _, err := image.Decode(file)
  36. if err != nil {
  37. log.Printf("解码图片失败: %v", err)
  38. return "", err
  39. }
  40. // 调整图片大小
  41. resizedImg := imaging.Thumbnail(img, maxDimension, maxDimension, imaging.Lanczos)
  42. // 获取输入文件的扩展名
  43. ext := filepath.Ext(imageSrc)
  44. ext = strings.ToLower(ext)
  45. // 生成输出文件名
  46. outputFileName := strings.TrimSuffix(imageSrc, ext) + "_resized" + ext
  47. outFile, err := os.Create(outputFileName)
  48. if err != nil {
  49. log.Printf("创建输出文件失败: %v", err)
  50. return "", err
  51. }
  52. defer outFile.Close()
  53. // 根据文件扩展名选择编码格式
  54. switch ext {
  55. case ".jpg", ".jpeg":
  56. err = imaging.Encode(outFile, resizedImg, imaging.JPEG, imaging.JPEGQuality(75))
  57. case ".png":
  58. err = imaging.Encode(outFile, resizedImg, imaging.PNG, imaging.PNGCompressionLevel(png.BestCompression))
  59. //case ".gif":
  60. // err = imaging.Encode(outFile, resizedImg, imaging.GIF, imaging.GIFNumColors(DW))
  61. default:
  62. log.Printf("不支持的图片格式: %s", ext)
  63. return "", err
  64. }
  65. if err != nil {
  66. log.Printf("编码图片失败: %v", err)
  67. return "", err
  68. }
  69. log.Println("图片压缩并保存成功:", outputFileName)
  70. return outputFileName, nil
  71. }