imageUtils.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package utils
  2. import (
  3. "github.com/disintegration/imaging"
  4. "image"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. )
  10. func ImageResize(imageSrc string, width, height int) (string, error) {
  11. file, err := os.Open(imageSrc)
  12. if err != nil {
  13. log.Printf("打开图片失败: %v", err)
  14. return "", err
  15. }
  16. defer file.Close()
  17. // 解码图片
  18. img, _, err := image.Decode(file)
  19. if err != nil {
  20. log.Printf("解码图片失败: %v", err)
  21. return "", err
  22. }
  23. // 调整图片大小
  24. resizedImg := imaging.Resize(img, width, height, imaging.Lanczos)
  25. // 获取输入文件的扩展名
  26. ext := filepath.Ext(imageSrc)
  27. ext = strings.ToLower(ext)
  28. // 生成输出文件名
  29. outputFileName := strings.TrimSuffix(imageSrc, ext) + "_resized" + ext
  30. outFile, err := os.Create(outputFileName)
  31. if err != nil {
  32. log.Printf("创建输出文件失败: %v", err)
  33. return "", err
  34. }
  35. defer outFile.Close()
  36. // 根据文件扩展名选择编码格式
  37. switch ext {
  38. case ".jpg", ".jpeg":
  39. err = imaging.Encode(outFile, resizedImg, imaging.JPEG, imaging.JPEGQuality(75))
  40. case ".png":
  41. err = imaging.Encode(outFile, resizedImg, imaging.PNG, imaging.PNGCompressionLevel(imaging.BestCompression))
  42. case ".gif":
  43. err = imaging.Encode(outFile, resizedImg, imaging.GIF
  44. imaging.GIFQuality(75))
  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. }