Parcourir la source

3,1优化图片

kobe6258 il y a 1 semaine
Parent
commit
d2fe39ed34
3 fichiers modifiés avec 68 ajouts et 2 suppressions
  1. 1 1
      controllers/image.go
  2. 3 1
      go.mod
  3. 64 0
      utils/imageUtils.go

+ 1 - 1
controllers/image.go

@@ -125,7 +125,7 @@ func (this *ImageController) AddImage() {
 	}
 
 	if req.SrcUrl == "" {
-		br.Msg = "音频地址为空"
+		br.Msg = "图片名称为空"
 		return
 	}
 

+ 3 - 1
go.mod

@@ -28,6 +28,7 @@ require (
 	github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d // indirect
 	github.com/cespare/xxhash/v2 v2.3.0 // indirect
 	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
+	github.com/disintegration/imaging v1.6.2 // indirect
 	github.com/dustin/go-humanize v1.0.1 // indirect
 	github.com/fatih/structs v1.1.0 // indirect
 	github.com/go-ini/ini v1.67.0 // indirect
@@ -64,9 +65,10 @@ require (
 	github.com/xuri/efp v0.0.0-20240408161823-9ad904a10d6d // indirect
 	github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 // indirect
 	golang.org/x/crypto v0.28.0 // indirect
+	golang.org/x/image v0.23.0 // indirect
 	golang.org/x/net v0.30.0 // indirect
 	golang.org/x/sys v0.26.0 // indirect
-	golang.org/x/text v0.19.0 // indirect
+	golang.org/x/text v0.21.0 // indirect
 	golang.org/x/time v0.6.0 // indirect
 	google.golang.org/genproto/googleapis/rpc v0.0.0-20240820151423-278611b39280 // indirect
 	gopkg.in/ini.v1 v1.67.0 // indirect

+ 64 - 0
utils/imageUtils.go

@@ -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
+}