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

34 lines
744 B
Go
Raw Permalink Normal View History

2024-02-22 14:14:11 -07:00
package lib
import (
"bytes"
2024-10-31 11:37:31 -06:00
"fmt"
2024-02-22 14:14:11 -07:00
"image"
"image/png"
"mime/multipart"
2024-02-22 14:14:11 -07:00
2024-10-31 11:37:31 -06:00
"golang.org/x/image/draw"
2024-02-22 14:14:11 -07:00
)
func ResizeImg(file multipart.File, width int, height int) ([]byte, error) {
2024-10-31 11:37:31 -06:00
// Read and decode image
img, _, err := image.Decode(file)
if err != nil {
return nil, fmt.Errorf("decode error: %w", err)
}
2024-02-22 14:14:11 -07:00
2024-10-31 11:37:31 -06:00
// Create new RGBA image
dst := image.NewRGBA(image.Rect(0, 0, width, height))
2024-02-22 14:14:11 -07:00
2024-10-31 11:37:31 -06:00
// Resize using high-quality interpolation
draw.CatmullRom.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Over, nil)
2024-02-22 14:14:11 -07:00
2024-10-31 11:37:31 -06:00
// Encode to PNG
buf := new(bytes.Buffer)
if err := png.Encode(buf, dst); err != nil {
return nil, fmt.Errorf("encode error: %w", err)
}
2024-02-22 14:14:11 -07:00
2024-10-31 11:37:31 -06:00
return buf.Bytes(), nil
2024-02-22 14:14:11 -07:00
}