Template
1
0
Fork 0
goth.stack/lib/img.go

40 lines
840 B
Go
Raw Normal View History

2024-02-22 14:14:11 -07:00
package lib
import (
"bytes"
"errors"
2024-02-22 14:14:11 -07:00
"image"
"image/png"
"io"
"mime/multipart"
2024-02-22 14:14:11 -07:00
"github.com/disintegration/imaging"
2024-02-22 14:14:11 -07:00
)
func ResizeImg(file multipart.File, width int, height int) ([]byte, error) {
2024-02-22 14:14:11 -07:00
// Read file content
fileContent, err := io.ReadAll(file)
if err != nil {
return nil, errors.New("error reading image file")
2024-02-22 14:14:11 -07:00
}
// Decode image
img, _, err := image.Decode(bytes.NewReader(fileContent))
if err != nil {
2024-02-23 00:51:49 -07:00
println(err.Error())
return nil, errors.New("error decoding image")
2024-02-22 14:14:11 -07:00
}
// Resize the image
resizedImg := imaging.Resize(img, width, height, imaging.Lanczos)
2024-02-22 14:14:11 -07:00
// Encode the resized image as PNG
buf := new(bytes.Buffer)
if err := png.Encode(buf, resizedImg); err != nil {
return nil, errors.New("error encoding image to PNG")
2024-02-22 14:14:11 -07:00
}
// Return the resized image as response
return buf.Bytes(), nil
2024-02-22 14:14:11 -07:00
}