78 lines
1.8 KiB
Go
78 lines
1.8 KiB
Go
package core
|
|
|
|
import (
|
|
"backend/util"
|
|
"errors"
|
|
"image"
|
|
"image/jpeg"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/disintegration/imaging"
|
|
)
|
|
|
|
func CompressImage(path string, name string) error {
|
|
// Creating folder
|
|
if err := os.MkdirAll(".temp", 0755); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Checking output file
|
|
if _, err := os.Stat(".temp/" + name + "_compressed.jpeg"); err == nil {
|
|
return errors.New("file already created")
|
|
}
|
|
// Create file
|
|
outputFile, err := os.Create(".temp/" + name + "_compressed.jpeg")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer outputFile.Close()
|
|
|
|
// Opening image + Reducing its size and quality
|
|
img, err := imaging.Open(path)
|
|
if err != nil {
|
|
return 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 {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func CompressFiles(basePath string) {
|
|
picd := GetPictureData()
|
|
count := 0
|
|
start := time.Now()
|
|
for _, p := range picd {
|
|
path := basePath + "/" + p.Album + "/" + p.Name
|
|
name := strings.TrimSuffix(p.Name, filepath.Ext(p.Name))
|
|
err := CompressImage(path, name)
|
|
if err != nil {
|
|
if strings.Compare(err.Error(), "file already created") != 0 {
|
|
util.Logformat(util.WARNING, "Failed to compress '%s' : (%v)\n", p.Name, err)
|
|
}
|
|
} else {
|
|
util.Logformatrn(util.INFO, "Compressing %d files...", count)
|
|
count++
|
|
}
|
|
}
|
|
if count > 0 {
|
|
elapsed := time.Since(start)
|
|
util.Logformatrn(util.CORRECT, "Compressed %d files in %dms.\n", count, elapsed.Milliseconds())
|
|
}
|
|
}
|