|
@@ -0,0 +1,64 @@
|
|
|
+package utils
|
|
|
+
|
|
|
+import (
|
|
|
+ "github.com/disintegration/imaging"
|
|
|
+ "image"
|
|
|
+ "log"
|
|
|
+ "os"
|
|
|
+ "path/filepath"
|
|
|
+ "strings"
|
|
|
+)
|
|
|
+
|
|
|
+func ImageResize(imageSrc string, width, height int) (string, error) {
|
|
|
+ file, err := os.Open(imageSrc)
|
|
|
+ if err != nil {
|
|
|
+ log.Printf("打开图片失败: %v", err)
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+ defer file.Close()
|
|
|
+
|
|
|
+ // 解码图片
|
|
|
+ img, _, err := image.Decode(file)
|
|
|
+ if err != nil {
|
|
|
+ log.Printf("解码图片失败: %v", err)
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+
|
|
|
+ // 调整图片大小
|
|
|
+ resizedImg := imaging.Resize(img, width, height, imaging.Lanczos)
|
|
|
+
|
|
|
+ // 获取输入文件的扩展名
|
|
|
+ ext := filepath.Ext(imageSrc)
|
|
|
+ ext = strings.ToLower(ext)
|
|
|
+
|
|
|
+ // 生成输出文件名
|
|
|
+ outputFileName := strings.TrimSuffix(imageSrc, ext) + "_resized" + ext
|
|
|
+ outFile, err := os.Create(outputFileName)
|
|
|
+ if err != nil {
|
|
|
+ log.Printf("创建输出文件失败: %v", err)
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+ defer outFile.Close()
|
|
|
+
|
|
|
+ // 根据文件扩展名选择编码格式
|
|
|
+ switch ext {
|
|
|
+ case ".jpg", ".jpeg":
|
|
|
+ err = imaging.Encode(outFile, resizedImg, imaging.JPEG, imaging.JPEGQuality(75))
|
|
|
+ case ".png":
|
|
|
+ err = imaging.Encode(outFile, resizedImg, imaging.PNG, imaging.PNGCompressionLevel(imaging.BestCompression))
|
|
|
+ case ".gif":
|
|
|
+ err = imaging.Encode(outFile, resizedImg, imaging.GIF
|
|
|
+ imaging.GIFQuality(75))
|
|
|
+ default:
|
|
|
+ log.Printf("不支持的图片格式: %s", ext)
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+
|
|
|
+ if err != nil {
|
|
|
+ log.Printf("编码图片失败: %v", err)
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+
|
|
|
+ log.Println("图片压缩并保存成功:", outputFileName)
|
|
|
+ return outputFileName, nil
|
|
|
+}
|