Removed image dependency
This commit is contained in:
40
lib/img.go
40
lib/img.go
@ -2,38 +2,32 @@ package lib
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"golang.org/x/image/draw"
|
||||
)
|
||||
|
||||
func ResizeImg(file multipart.File, width int, height int) ([]byte, error) {
|
||||
// Read file content
|
||||
fileContent, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
return nil, errors.New("error reading image file")
|
||||
}
|
||||
// Read and decode image
|
||||
img, _, err := image.Decode(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode error: %w", err)
|
||||
}
|
||||
|
||||
// Decode image
|
||||
img, _, err := image.Decode(bytes.NewReader(fileContent))
|
||||
if err != nil {
|
||||
println(err.Error())
|
||||
return nil, errors.New("error decoding image")
|
||||
}
|
||||
// Create new RGBA image
|
||||
dst := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
|
||||
// Resize the image
|
||||
resizedImg := imaging.Resize(img, width, height, imaging.Lanczos)
|
||||
// Resize using high-quality interpolation
|
||||
draw.CatmullRom.Scale(dst, dst.Bounds(), img, img.Bounds(), draw.Over, nil)
|
||||
|
||||
// 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")
|
||||
}
|
||||
// Encode to PNG
|
||||
buf := new(bytes.Buffer)
|
||||
if err := png.Encode(buf, dst); err != nil {
|
||||
return nil, fmt.Errorf("encode error: %w", err)
|
||||
}
|
||||
|
||||
// Return the resized image as response
|
||||
return buf.Bytes(), nil
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user