imageUtils.go 1.5 KB

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