feat: add webp conversion for images

This commit is contained in:
log101 2024-07-03 22:28:20 +03:00
parent ca4e157acd
commit 7706dd122e
4 changed files with 46 additions and 0 deletions

1
go.mod
View File

@ -7,6 +7,7 @@ require github.com/gofiber/fiber/v2 v2.52.5
require (
github.com/andybalholm/brotli v1.0.5 // indirect
github.com/google/uuid v1.5.0 // indirect
github.com/h2non/bimg v1.1.9 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect

2
go.sum
View File

@ -4,6 +4,8 @@ github.com/gofiber/fiber/v2 v2.52.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yG
github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/h2non/bimg v1.1.9 h1:WH20Nxko9l/HFm4kZCA3Phbgu2cbHvYzxwxn9YROEGg=
github.com/h2non/bimg v1.1.9/go.mod h1:R3+UiYwkK4rQl6KVFTOFJHitgLbZXBZNFh2cv3AEbp8=
github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM=
github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=

BIN
public/delirot.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

View File

@ -2,19 +2,29 @@ package main
import (
"fmt"
"io"
"os"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/h2non/bimg"
)
func main() {
app := fiber.New()
app.Use(logger.New())
app.Use(compress.New(compress.Config{
Level: compress.LevelBestCompression,
}))
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Sample")
})
app.Static("/images", "./public")
app.Post("/upload", func(c *fiber.Ctx) error {
if form, err := c.MultipartForm(); err == nil {
if token := form.Value["token"]; len(token) > 0 {
@ -25,6 +35,38 @@ func main() {
for _, file := range files {
fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0])
// Save the files to disk:
// if err := c.SaveFile(file, fmt.Sprintf("./public/%s", file.Filename)); err != nil {
// return err
// }
/*
buffer, err := bimg.Read(file.Filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
*/
newFile, err := file.Open()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
defer newFile.Close()
data, err := io.ReadAll(newFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
newImage, err := bimg.NewImage(data).Convert(bimg.WEBP)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
imageName := strings.Split(file.Filename, ".")[0]
bimg.Write(fmt.Sprintf("./public/%s.webp", imageName), newImage)
}
return err
@ -34,4 +76,5 @@ func main() {
})
app.Listen(":3000")
}