You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.8 KiB

package file
import (
"bytes"
"github.com/disintegration/imaging"
"github.com/gin-gonic/gin"
"image/jpeg"
"image/png"
"path/filepath"
"recook/internal/back"
"recook/internal/static_path"
"strconv"
"strings"
"sync"
)
var once sync.Once
var notFindPhoto []byte
func getNotFindPhoto() []byte {
once.Do(func() {
path := filepath.Join(static_path.Dir.Root, static_path.Dir.Default, "404.jpg")
img, _ := imaging.Open(path)
buffer := new(bytes.Buffer)
_ = jpeg.Encode(buffer, img, nil)
notFindPhoto = buffer.Bytes()
})
return notFindPhoto
}
// ===================================================
// ============== 读取文件 =============
// ===================================================
func ResizePhotos(c *gin.Context) {
path := c.Param("path")
pathArr := strings.Split(strings.Trim(path, "/"), "/")
pathLen := len(pathArr)
if pathLen < 3 {
back.Err(c, "png转码出错")
return
}
dir := filepath.Join(pathArr[0 : pathLen-2]...)
name := pathArr[pathLen-2]
sizeStr := pathArr[pathLen-1]
size := 0
if len(sizeStr) > 0 {
s, err := strconv.Atoi(sizeStr)
if err != nil {
back.Err(c, err.Error())
return
}
size = s
}
// 打开图片
path = filepath.Join(static_path.Dir.Root, dir, name)
img, err := imaging.Open(path)
if err != nil {
c.Data(200, "image/jpeg", getNotFindPhoto())
return
}
if size > 0 && size < img.Bounds().Max.X {
img = imaging.Resize(img, size, 0, imaging.Lanczos)
}
buffer := new(bytes.Buffer)
if strings.Contains(name, "png") {
if err := png.Encode(buffer, img); err != nil {
back.Err(c, "png转码出错")
return
}
c.Data(200, "image/png", buffer.Bytes())
} else {
if err := jpeg.Encode(buffer, img, nil); err != nil {
back.Err(c, "jpeg转码出错")
return
}
c.Data(200, "image/jpeg", buffer.Bytes())
}
}