2024-02-22 14:14:11 -07:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2024-02-22 14:39:14 -07:00
|
|
|
"errors"
|
2024-02-22 14:14:11 -07:00
|
|
|
"image"
|
|
|
|
"image/png"
|
|
|
|
"io"
|
2024-02-22 14:39:14 -07:00
|
|
|
"mime/multipart"
|
2024-02-22 14:14:11 -07:00
|
|
|
|
2024-02-29 10:31:26 -07:00
|
|
|
"github.com/disintegration/imaging"
|
2024-02-22 14:14:11 -07:00
|
|
|
)
|
|
|
|
|
2024-02-22 14:39:14 -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 {
|
2024-02-29 10:31:26 -07:00
|
|
|
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())
|
2024-02-29 10:31:26 -07:00
|
|
|
return nil, errors.New("error decoding image")
|
2024-02-22 14:14:11 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Resize the image
|
2024-02-29 10:31:26 -07:00
|
|
|
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 {
|
2024-02-29 10:31:26 -07:00
|
|
|
return nil, errors.New("error encoding image to PNG")
|
2024-02-22 14:14:11 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// Return the resized image as response
|
2024-02-22 14:39:14 -07:00
|
|
|
return buf.Bytes(), nil
|
2024-02-22 14:14:11 -07:00
|
|
|
}
|