atri.dad/lib/img.go

41 lines
865 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"
2024-02-23 00:51:49 -07:00
_ "image/jpeg"
2024-02-22 14:14:11 -07:00
"image/png"
"io"
"mime/multipart"
2024-02-22 14:14:11 -07:00
"github.com/anthonynsimon/bild/transform"
)
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 := transform.Resize(img, width, height, transform.Linear)
// 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
}