46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
package core
|
|
|
|
import (
|
|
"backend/util"
|
|
"image"
|
|
"image/jpeg"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/disintegration/imaging"
|
|
)
|
|
|
|
func CompressImage(path string) {
|
|
// Creating folder + output file
|
|
if err := os.MkdirAll(filepath.Dir(".temp"), 0755); err != nil {
|
|
util.Logformatrn(util.ERROR, "Failed to create temp directory (%v)", err)
|
|
return
|
|
}
|
|
outputFile, err := os.Create(".temp/test.jpeg")
|
|
if err != nil {
|
|
util.Logformatrn(util.ERROR, "Failed to create file: %v", err)
|
|
}
|
|
defer outputFile.Close()
|
|
|
|
// Opening image + Reducing its size and quality
|
|
img, err := imaging.Open(path)
|
|
if err != nil {
|
|
util.Logformatrn(util.ERROR, "Failed to open image: %v", err)
|
|
}
|
|
width := float64(img.Bounds().Dx())
|
|
height := float64(img.Bounds().Dy())
|
|
ratio := float64(0)
|
|
var imgOutput *image.NRGBA
|
|
if width < height {
|
|
ratio = height / width
|
|
imgOutput = imaging.Resize(img, 283, int(283*ratio), imaging.Lanczos)
|
|
} else {
|
|
ratio = width / height
|
|
imgOutput = imaging.Resize(img, int(283*ratio), 283, imaging.Lanczos)
|
|
}
|
|
|
|
// Encoding to jpeg afterwards
|
|
if err := jpeg.Encode(outputFile, imgOutput, &jpeg.Options{Quality: 30}); err != nil {
|
|
util.Logformatrn(util.ERROR, "Failed to save image: %v", err)
|
|
}
|
|
}
|