123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- package utils
- import (
- "github.com/disintegration/imaging"
- "image"
- "image/png"
- "log"
- "mime/multipart"
- "os"
- "path/filepath"
- "strings"
- )
- var (
- imgExtMap = map[string]string{
- ".jpg": "image/jpeg",
- ".jpeg": "image/jpeg",
- ".png": "image/png",
- }
- )
- func CheckImageFormat(fileName string, file multipart.File, header *multipart.FileHeader) bool {
- ext := strings.ToLower(filepath.Ext(fileName))
- contentType := header.Header.Get("Content-Type")
- if imgExtMap[ext] == contentType {
- return true
- }
- return false
- }
- func ImageResize(imageSrc string, maxDimension 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.Thumbnail(img, maxDimension, maxDimension, 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(png.BestCompression))
- //case ".gif":
- // err = imaging.Encode(outFile, resizedImg, imaging.GIF, imaging.GIFNumColors(DW))
- default:
- log.Printf("不支持的图片格式: %s", ext)
- return "", err
- }
- if err != nil {
- log.Printf("编码图片失败: %v", err)
- return "", err
- }
- log.Println("图片压缩并保存成功:", outputFileName)
- return outputFileName, nil
- }
|