Kaynağa Gözat

[backend] Add image resize

Dima 1 yıl önce
ebeveyn
işleme
5d4924140e
3 değiştirilmiş dosya ile 45 ekleme ve 7 silme
  1. BIN
      build/app/app
  2. 6 4
      go.mod
  3. 39 3
      internal/repositories/file.go

BIN
build/app/app


+ 6 - 4
go.mod

@@ -5,6 +5,7 @@ go 1.19
 require (
 	github.com/Masterminds/squirrel v1.5.3
 	github.com/brianvoe/gofakeit/v6 v6.19.0
+	github.com/disintegration/imaging v1.6.2
 	github.com/go-playground/validator/v10 v10.11.1
 	github.com/gofiber/fiber/v2 v2.42.0
 	github.com/gofiber/jwt/v3 v3.3.6
@@ -58,10 +59,11 @@ require (
 	github.com/valyala/bytebufferpool v1.0.0 // indirect
 	github.com/valyala/fasthttp v1.44.0 // indirect
 	github.com/valyala/tcplisten v1.0.0 // indirect
-	golang.org/x/net v0.4.0 // indirect
-	golang.org/x/sys v0.3.0 // indirect
-	golang.org/x/text v0.5.0 // indirect
-	golang.org/x/tools v0.3.0 // indirect
+	golang.org/x/image v0.11.0 // indirect
+	golang.org/x/net v0.6.0 // indirect
+	golang.org/x/sys v0.5.0 // indirect
+	golang.org/x/text v0.12.0 // indirect
+	golang.org/x/tools v0.6.0 // indirect
 	gopkg.in/ini.v1 v1.67.0 // indirect
 	gopkg.in/yaml.v3 v3.0.1 // indirect
 )

+ 39 - 3
internal/repositories/file.go

@@ -9,10 +9,15 @@ import (
 	"os"
 
 	"git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
+	"github.com/disintegration/imaging"
 	"github.com/gofiber/fiber/v2"
 )
 
-const uploadPath = "../../web/public"
+const (
+	uploadPath   = "../../web/public"
+	resizeWidth  = 1000
+	resizeHeight = 800
+)
 
 type fileRepository struct{}
 
@@ -21,9 +26,40 @@ func InitFileRepository() interfaces.FileRepository {
 }
 
 func (r fileRepository) Save(fctx *fiber.Ctx, header *multipart.FileHeader, path string) error {
-	return fctx.SaveFile(header, uploadPath+path)
+	fullPath := getFullPath(path)
+
+	if err := fctx.SaveFile(header, fullPath); err != nil {
+		return err
+	}
+
+	// Resize image
+	src, err := imaging.Open(fullPath)
+	if err != nil {
+		return err
+	}
+
+	origHeight := src.Bounds().Size().Y
+	origWidth := src.Bounds().Size().X
+	var newHeight, newWidth int
+
+	if origWidth > origHeight {
+		newWidth = resizeWidth
+	} else {
+		newHeight = resizeHeight
+	}
+
+	dst := imaging.Resize(src, newWidth, newHeight, imaging.Lanczos)
+	if err = imaging.Save(dst, fullPath); err != nil {
+		return err
+	}
+
+	return nil
 }
 
 func (r fileRepository) Delete(path string) error {
-	return os.RemoveAll(uploadPath + path)
+	return os.RemoveAll(getFullPath(path))
+}
+
+func getFullPath(path string) string {
+	return uploadPath + path
 }